工厂方法 VS 工厂对象
据我了解,工厂方法是简单工厂,工厂对象是抽象工厂? 并且:
-工厂方法(简单工厂):
public class SimplePizzaFactory {
public static final int CHEESE = 1;
public static final int PEPPERONI = 2;
public static final int VEGGIE = 3;
public static Pizza createPizza(int type) {
Pizza pizza = null;
if (type == CHEESE) {
pizza = new CheesePizza();
} else if (type == PEPPERONI ) {
pizza = new PepperoniPizza();
} else if (type == VEGGIE ) {
pizza = new VeggiePizza();
}
return pizza;
}
}
工厂对象(抽象工厂)
:?
我说得对吗?
工厂模式有多少种实现,它们有什么区别?
As I understand Factory Method is Simple Factory and Factory Object is Abstract Factory?
And:
-Factory Method (Simple Factory):
public class SimplePizzaFactory {
public static final int CHEESE = 1;
public static final int PEPPERONI = 2;
public static final int VEGGIE = 3;
public static Pizza createPizza(int type) {
Pizza pizza = null;
if (type == CHEESE) {
pizza = new CheesePizza();
} else if (type == PEPPERONI ) {
pizza = new PepperoniPizza();
} else if (type == VEGGIE ) {
pizza = new VeggiePizza();
}
return pizza;
}
}
Factory Object(Abstract Factory):
?
Am I right?
How much are there realizations of Factory patterns and what is their difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。工厂方法是不需要任何状态的工厂。工厂类本身就是一个类 - 它具有状态以及改变该状态的方法。最后,您调用
.create()
方法,它使用其当前状态创建不同类型的新对象。抽象工厂是另一回事——同一个抽象概念有多个工厂实现。 wikipedia 示例 是关于 e
GUIFactory
- 这是一个抽象工厂,它有两个实现:WinFactory
和OSXFactory
。客户端代码不知道它正在使用哪个实现 - 它只知道工厂创建Button
实例。这使得无论操作系统如何都可以编写相同的代码。No. A factory-method is a factory that does not require any state. A factory class is a class itself - it has state, and methods that alter that state. In the end you call the
.create()
method, and it uses its current state to create a new object of a different type.Abstract factory is a different thing - there you have multiple factory implementations of the same abstract concept. The wikipedia example is about e
GUIFactory
- this is an abstract factory, which has two implementations:WinFactory
andOSXFactory
. The client code does not know which implementation it is using - it just knows the factory createsButton
instances. Which make it possible to write the same code regardless of the OS.