我知道有很多关于这两种模式之间差异的帖子,但有一些东西我找不到。
From what I have been reading, I see that the factory method pattern allows you to define how to create a single concrete product but hiding the implementation from the client as they will see a generic product. My first question is about the abstract factory. Is its role to allow you to create families of concrete objects in (that can depend on what specific factory you use) rather than just a single concrete object? Does the abstract factory only return one very large object or many objects depending on what methods you call?
我最后两个问题是关于一句我在很多地方都见过的引语,我不能完全理解:
两者之间的一个区别是
使用抽象工厂模式,a
类委托的责任
对象实例化到另一个对象
通过合成,而工厂
方法模式使用继承和
类依赖于子类来处理
所需的对象实例化。
我的理解是,工厂方法模式有一个Creator接口,它将使ConcreteCreator负责知道要实例化哪个ConcreteProduct。这就是使用继承来处理对象实例化的意思吗?
现在,关于引用,抽象工厂模式是如何通过组合将对象实例化的责任委托给另一个对象的?这是什么意思?在我看来,抽象工厂模式似乎也使用继承来完成构造过程,但我仍然在学习这些模式。
任何帮助,特别是最后一个问题,将非常感激。
A)工厂方法模式
工厂方法是一种创建设计模式,它提供了创建对象的接口,但允许子类改变将要创建的对象的类型。
如果在基类和扩展它的子类中有一个创建方法,您可能会考虑工厂方法。
B)抽象工厂模式
抽象工厂是一种创造性的设计模式,允许在不指定具体类的情况下产生相关或依赖的对象族。
什么是“对象族”?例如,以这组类为例:传输+引擎+控制。这些可能有几种变体:
1-汽车+内燃机+方向盘
2-平面+ JetEngine +轭
如果你的程序不使用产品族,那么你就不需要抽象工厂。
同样,很多人混淆了抽象工厂模式和简单的工厂类声明为抽象。不要那样做!
裁判:https://refactoring.guru/design-patterns/factory-comparison
Understand the differences in the motivations:
Suppose you’re building a tool where you’ve objects and a concrete implementation of the interrelations of the objects. Since you foresee variations in the objects, you’ve created an indirection by assigning the responsibility of creating variants of the objects to another object (we call it abstract factory). This abstraction finds strong benefit since you foresee future extensions needing variants of those objects.
Another rather intriguing motivation in this line of thoughts is a case where every-or-none of the objects from the whole group will have a corresponding variant. Based on some conditions, either of the variants will be used and in each case all objects must be of same variant. This might be a bit counter intuitive to understand as we often tend think that - as long as the variants of an object follow a common uniform contract (interface in broader sense), the concrete implementation code should never break. The intriguing fact here is that, not always this is true especially when expected behavior cannot be modeled by a programming contract.
A simple (borrowing the idea from GoF) is any GUI applications say a virtual monitor that emulates look-an-feel of MS or Mac or Fedora OS’s. Here, for example, when all widget objects such as window, button, etc. have MS variant except a scroll-bar that is derived from MAC variant, the purpose of the tool fails badly.
These above cases form the fundamental need of Abstract Factory Pattern.
On the other hand, imagine you’re writing a framework so that many people can built various tools (such as the one in above examples) using your framework. By the very idea of a framework, you don’t need to, albeit you could not use concrete objects in your logic. You rather put some high level contracts between various objects and how they interact. While you (as a framework developer) remain at a very abstract level, each builders of the tool is forced to follow your framework-constructs. However, they (the tool builders) have the freedom to decide what object to be built and how all the objects they create will interact. Unlike the previous case (of Abstract Factory Pattern), you (as framework creator) don’t need to work with concrete objects in this case; and rather can stay at the contract level of the objects. Furthermore, unlike the second part of the previous motivations, you or the tool-builders never have the situations of mixing objects from variants. Here, while framework code remains at contract level, every tool-builder is restricted (by the nature of the case itself) to using their own objects. Object creations in this case is delegated to each implementer and framework providers just provide uniform methods for creating and returning objects. Such methods are inevitable for framework developer to proceed with their code and has a special name called Factory method (Factory Method Pattern for the underlying pattern).
Few Notes:
If you’re familiar with ‘template method’, then you’d see that factory methods are often invoked from template methods in case of programs pertaining to any form of framework. By contrast, template methods of application-programs are often simple implementation of specific algorithm and void of factory-methods.
Furthermore, for the completeness of the thoughts, using the framework (mentioned above), when a tool-builder is building a tool, inside each factory method, instead of creating a concrete object, he/she may further delegate the responsibility to an abstract-factory object, provided the tool-builder foresees variations of the concrete objects for future extensions.
Sample Code:
//Part of framework-code
BoardGame {
Board createBoard() //factory method. Default implementation can be provided as well
Piece createPiece() //factory method
startGame(){ //template method
Board borad = createBoard()
Piece piece = createPiece()
initState(board, piece)
}
}
//Part of Tool-builder code
Ludo inherits BoardGame {
Board createBoard(){ //overriding of factory method
//Option A: return new LudoBoard() //Lodu knows object creation
//Option B: return LudoFactory.createBoard() //Lodu asks AbstractFacory
}
….
}
//Part of Tool-builder code
Chess inherits BoardGame {
Board createBoard(){ //overriding of factory method
//return a Chess board
}
….
}
两者的区别
“工厂方法”和“抽象工厂”的主要区别在于,工厂方法是方法,而抽象工厂是对象。我想很多人都把这两个词搞混了,开始交替使用。我记得当我学习它们的时候,我很难找到它们之间的确切区别。
因为工厂方法只是一个方法,它可以在子类中被重写,因此引用的后半部分:
... 工厂方法模式使用的
继承并依赖于一个子类
来处理所需的对象
实例化。
引用假设对象在这里调用自己的工厂方法。因此,唯一可以改变返回值的是子类。
抽象工厂是一个具有多个工厂方法的对象。看看你引言的前半部分:
... 使用抽象工厂模式,一个类
委托对象的职责
实例化到另一个对象
作文……
他们说的是,有一个对象A,想要创建一个Foo对象。而不是创建Foo对象本身(例如,使用工厂方法),它将获得一个不同的对象(抽象工厂)来创建Foo对象。
代码示例
为了向你展示区别,这里有一个正在使用的工厂方法:
class A {
public void doSomething() {
Foo f = makeFoo();
f.whatever();
}
protected Foo makeFoo() {
return new RegularFoo();
}
}
class B extends A {
protected Foo makeFoo() {
//subclass is overriding the factory method
//to return something different
return new SpecialFoo();
}
}
这是一个正在使用的抽象工厂:
class A {
private Factory factory;
public A(Factory factory) {
this.factory = factory;
}
public void doSomething() {
//The concrete class of "f" depends on the concrete class
//of the factory passed into the constructor. If you provide a
//different factory, you get a different Foo object.
Foo f = factory.makeFoo();
f.whatever();
}
}
interface Factory {
Foo makeFoo();
Bar makeBar();
Aycufcn makeAmbiguousYetCommonlyUsedFakeClassName();
}
//need to make concrete factories that implement the "Factory" interface here
工厂设计模式
generation 1 <- generation 2 <- generation 3
//example
(generation 1) shape <- (generation 2) rectangle, oval <- (generation 3) rectangle impressionism, rectangle surrealism, oval impressionism, oval surrealism
工厂
用例:实例化第2代的一个对象
这是一种创造模式,允许你在一个简单的地方创建第2代。它符合SRP和OCP -所有的更改都在一个类中进行。
enum ShapeType {
RECTANGLE,
OVAL
}
class Shape {}
//Concrete Products
//generation 2
class Rectangle extends Shape {}
class Oval extends Shape {}
//Factory
class Factory {
Shape createShape(ShapeType type) {
switch (type) {
case RECTANGLE:
return new Rectangle();
case OVAL:
return new Oval();
}
}
}
//Creator
class Painter {
private Factory factory;
Painter(Factory factory) {
this.factory = factory;
}
Shape prepareShape(ShapeType type) {
return factory.createShape(type);
}
}
//using
class Main {
void main() {
Painter painter = new Painter(new Factory());
Shape shape1 = painter.prepareShape(ShapeType.RECTANGLE);
Shape shape2 = painter.prepareShape(ShapeType.OVAL);
}
}
工厂方法
用例:实例化第3代的一个对象
有助于与下一代家庭成员合作。每个画家都有自己的风格,印象派、超现实主义……工厂方法使用抽象创造者作为工厂(抽象方法),具体创造者是这种方法的实现
enum ShapeType {
RECTANGLE,
OVAL
}
class Shape {}
//Concrete Products
//generation 2
class Rectangle extends Shape {}
class Oval extends Shape {}
//generation 3
class RectangleImpressionism extends Rectangle {}
class OvalImpressionism extends Oval {}
class RectangleSurrealism extends Rectangle {}
class OvalSurrealism extends Oval {}
//Creator
abstract class Painter {
Shape prepareShape(ShapeType type) {
return createShape(type);
}
//Factory method
abstract Shape createShape(ShapeType type);
}
//Concrete Creators
class PainterImpressionism {
@override
Shape createShape(ShapeType type) {
switch (type) {
case RECTANGLE:
return new RectangleImpressionism();
case OVAL:
return new OvalImpressionism();
}
}
}
class PainterSurrealism {
@override
Shape createShape(ShapeType type) {
switch (type) {
case RECTANGLE:
return new RectangleSurrealism();
case OVAL:
return new OvalSurrealism();
}
}
}
//using
class Main {
void main() {
Painter painterImpressionism = new PainterImpressionism();
Shape shape1 = painterImpressionism.prepareShape(ShapeType.RECTANGLE);
Painter painterSurrealism = new PainterSurrealism();
Shape shape2 = painterSurrealism.prepareShape(ShapeType.RECTANGLE);
}
}
抽象工厂
用例:实例化第3代的所有对象
工厂是抽象工厂和具象工厂的一部分
//Concrete Products
//generation 2
class Rectangle extends Shape {}
class Oval extends Shape {}
//generation 3
class RectangleImpressionism extends Rectangle {}
class OvalImpressionism extends Oval {}
class RectangleSurrealism extends Rectangle {}
class OvalSurrealism extends Oval {}
//Abstract Factory
interface Factory {
Rectangle createRectangle();
Oval createOval();
}
//Concrete Factories
class ImpressionismFactory implements Factory {
@Override
public Rectangle createRectangle() {
return new RectangleImpressionism();
}
@Override
public Oval createOval() {
return new OvalImpressionism();
}
}
class SurrealismFactory implements Factory {
@Override
public Rectangle createRectangle() {
return new RectangleSurrealism();
}
@Override
public Oval createOval() {
return new OvalSurrealism();
}
}
//Creator
class Painter {
Rectangle rectangle;
Oval oval;
Painter(Factory factory) {
rectangle = factory.createRectangle();
rectangle.resize();
oval = factory.createOval();
oval.resize();
}
}
//using
class Main {
void main() {
Painter painter1 = new Painter(new ImpressionismFactory());
Shape shape1 = painter1.rectangle;
Shape shape2 = painter1.oval;
Painter painter2 = new Painter(new ImpressionismFactory());
Shape shape3 = painter2.rectangle;
Shape shape4 = painter1.oval;
}
}