【发布时间】:2012-09-06 05:21:57
【问题描述】:
我正在阅读有关工厂方法模式的信息。
我可以理解何时有一个工厂类,即StoreFactory#getStore(),它基于某个运行时或其他状态返回一个Store 实现。
但是,从阅读(例如this link)来看,似乎人们创建一个抽象工厂类的一般模式,其他工厂类扩展到该类:
public abstract class AbstractFactory {
public abstract Store getStore(int store);
}
public class StoreFactoryA extends AbstractFactory {
public Store getStore(int Store) {
if(Store == 1) { return new MyStoreImplA(); }
if(Store == 2) { return new MyStoreImplB(); }
}
}
public class StoreFactoryB extends AbstractFactory {
public Store getStore(int Store) {
if(Store == 1) { return new MyStoreImplC(); }
if(Store == 2) { return new MyStoreImplD(); }
}
}
public class Runner {
public static void main(String[] args) {
AbstractFactory storeFactory = new StoreFactoryA();
Store myStore = storeFactory.getStore(1);
}
}
我的示例是人为设计的,但模拟了上述链接的示例。
这个实现对我来说似乎有点像鸡蛋。使用工厂方法模式消除了客户端代码指定类类型的需要,但现在客户端代码需要选择性地选择要使用的正确工厂,即StoreFactoryA、StoreFactoryB?
这里使用抽象类的原因是什么?
【问题讨论】:
-
你的例子有点太简单了。 abstract 工厂的意义在于,您可以 a) 在运行时选择整个工厂,然后 b) 使 那个 工厂产生整个对象集合。逻辑分组是最重要的。这可以防止您混合应该属于不同工厂并且实际上不可能同时出现的两种对象类型。
-
@KerrekSB:这应该是一个答案。
-
@casablanca:谢谢,虽然我认为 Sameer 的回答基本上是一样的,而且做得很好。
-
@KerrekSB:啊,看来他是在我发表评论后才发布的。 :)
标签: java design-patterns factory-pattern