(Head First)设计模式基础

一,工厂模式

所以设计模式的一个重要目就是将系统中经常变化的部分从相对固定的部分抽离出来,减少代码变更可能对系统造成的影响。即开闭原则。

All factory patterns encapsulate object creation. The Factory Method Pattern encapsulates
object creation by letting subclasses decide what objects to create.
 
工厂方法其实可以看做一个框架(半成品),编写一个实现工厂方法的子类,便可开始工作。
简单工厂可以封装对象创建细节,但是没有工厂方法那样强的灵活性,适应性。因为简单工厂不能根据不同的需求对应的调整对象创建细节。

Q: I’m still a bit confused about the difference
between Simple Factory and Factory Method. They
look very similar, except that in Factory Method, the
class that returns the pizza is a subclass. Can you
explain?
A: You’re right that the subclasses do look a lot
like Simple Factory, however think of Simple Factory
as a one shot deal, while with Factory Method you are
creating a framework that let’s the subclasses decide
which implementation will be used. For example, the
orderPizza() method in the Factory Method provides a
general framework for creating pizzas that relies on a
factory method to actually create the concrete classes
that go into making a pizza. By subclassing the
PizzaStore class, you decide what concrete products
go into making the pizza that orderPizza() returns.
Compare that with SimpleFactory, which gives you a
way to encapsulate object creation, but doesn’t give
you the flexibility of the Factory Method because there
is no way to vary the products you’re creating.

抽象工厂模式与工厂方法模式

抽象工厂模式的具体工厂在创建产品时使用了工厂方法。抽象工厂只是用来创建产品。

工厂方法模式通常会把消费产品的方法直接写在抽象建造者中。

HeadFirst: Abstract Factory, I heard that you often use
factory methods to implement your concrete factories?
Abstract Factory: Yes, I’ll admit it, my concrete
factories often implement a factory method to create
their products. In my case, they are used purely to create
products...
Factory Method: ...while in my case I usually
implement code in the abstract creator that makes use of
the concrete types the subclasses create.

工厂方法的焦点在于声明了一个抽象方法,属于方法级别的模式,适合管理一个产品。抽象工厂的核心在于声明一套相关产品创建的接口,属于类级别的模式,适合管理一套产品。

原文地址:https://www.cnblogs.com/wllhq/p/13627104.html