4

我试图更好地掌握工厂模式,如下所示:

http://www.oodesign.com/factory-pattern.html

这些示例是用 Java 编写的,我不是一个非常强大的 Java 程序员。我主要不明白这Constructor product ... = cClass... String.class条线。我想我已经有了“概念”,但这两个代码块是相似的吗?

此外,Cocoa Foundation 中是否有使用此模式的示例?我能想到的唯一一个是在 UIKit 中针对UITableView.

爪哇:

class ProductFactory
{
    private HashMap m_RegisteredProducts = new HashMap();

    public void registerProduct (String productID, Class productClass)
    {
        m_RegisteredProducts.put(productID, productClass);
    }

    public Product createProduct(String productID)
    {
        Class productClass = (Class)m_RegisteredProducts.get(productID);
        Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
        return (Product)productConstructor.newInstance(new Object[] { });
    }
}

目标-C:

@interface ProductFactory : NSObject

- (void)registerProduct:(Class)productClass withIdentifier:(NSString *)identifier;
- (id)newProductForIdentifier:(NSString *)identifier;

@end

@interface ProductFactory();

@property (strong, nonatomic) NSMutableDictionary *registeredProducts;

@end

@implementation ProductFactory

- (id)init
{
    self = [super init];
    if (self) {
        _registeredProducts = [NSMutableDictionary dictionary];
    }

    return self;
}

- (void)registerProduct:(Class)productClass withIdentifier:(NSString *)identifier
{
    self.registeredProducts[identifier] = NSStringFromClass(productClass);
}

- (id)newProductForIdentifier:(NSString *)identifier
{
    NSString *classString = self.registeredProducts[identifier];
    Class productClass = NSClassFromString(classString);

    return [[productClass alloc] init];
}

@end
4

1 回答 1

1

Yes, that is generally analogous. I haven't done java for a little while so I can't explicitly explain the Constructor line but it's kind of like the definition of a designated initialiser and how to find it.

You could do a little work with @protocols to allow a range of init methods to be available for the instantiation and interrogate the class to see which protocol it conforms to (using conformsToProtocol:).

于 2013-06-20T16:13:31.677 回答