我试图更好地掌握工厂模式,如下所示:
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