【问题标题】:Factory Pattern - Example in Objective-C工厂模式 - Objective-C 中的示例
【发布时间】:2013-06-20 15:39:58
【问题描述】:

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

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

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

此外,Cocoa Foundation 中是否有使用此模式的示例?我能想到的唯一一个是在 UIKit 中针对 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[] { });
    }
}

目标-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

【问题讨论】:

    标签: objective-c oop factory


    【解决方案1】:

    是的,这通常是类似的。我有一段时间没学过java,所以我无法明确解释Constructor这一行,但它有点像指定初始化程序的定义以及如何找到它。

    您可以使用@protocols 做一些工作,以允许一系列初始化方法可用于实例化并询问类以查看它符合哪个协议(使用conformsToProtocol:)。

    【讨论】:

    • 关于conformsToProtocol:的好主意!
    猜你喜欢
    • 2011-01-07
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多