I am trying to better understand the Factory pattern as shown here:
http://www.oodesign.com/factory-pattern.html
Examples in Java, and I'm not a very strong Java programmer. Basically I don't understand the line Constructor product ... = cClass... String.class . I think I have a "concept", but are these two blocks of code similar?
Also, is there an example in Cocoa Foundation that uses this template? The only one I can think of is in UIKit registering cell classes against UITableView .
Java:
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
source share