我正在尝试更好地掌握工厂模式,如下所示: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[] { });
}
}
Objective-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
conformsToProtocol:
的想法很不错! - edelaney05