Factory Sample - Example in Objective-C

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 
+4
source share
1 answer

Yes, this is usually the same. I didn’t do java a bit, so I can’t explain the Constructor line explicitly, but this is similar to the definition of the designated initializer and how to find it.

You can work a bit with @protocol to allow access to a number of init methods for instantiating and querying the class to see which protocol it matches (using conformsToProtocol: .

+1
source

Source: https://habr.com/ru/post/1487326/


All Articles