设计模式笔记感悟 - Creational篇
1. Prototype Pattern ( 原型模式 )
关键:
继承 ICanClone 接口.
理解:
原型实例从语法上看是一个对象(实例), 但是从功能上看是一个类 -- 当我们实现了一个原型( 即一个原型对象 ), 便可以利用 clone() 函数构造出无数个 跟这个原型的行为方式一模一样的实例. 这不就是 new Class() 的功能么?
clone() 与 new Class() 不同的是: 类是在编译过程之前定义的, 其行为方式在编译之后很难改变. 而原型对象的行为方式可以通过配置子组件, 设置参数来改变, 所以更加灵活.
注意:
对象内部有循环引用
clone() 函数的实现.
2. Abstract Factory ( 抽象工厂模式 )

关键:
产品族
理解:
具体类的创建代码不会在客户端程序中. 更方便的替换大量具体类.
一个具体抽象工厂类对应着一个产品族. 不用关心产品族下面的实现, 只调用抽象工厂类的公共方法.
3. Factory Method( 工厂方法模式 )
关键:
用 createProduct():IProduct 来代替 new Product();
理解:
1. “Creating objects inside a class with a factory method is always more flexible than creating an object directly” – < Design Patterns – GoF >
createProduct():IProduct 方法可以被继承来改变"生产"出来的具体Product. 而 new Product() 方法是硬代码, 无法通过继承来修改具体返回Product.
如果我们需要换掉原来的Product具体类而使用新的 Product具体类, 一般有两种方式: 一种是继承原来的 creater 类, 覆盖createProduct()方法; 第二种是直接修改 creater 的 createProduct() 方法.
不管使用哪种方式, 与 new Product() 方式相比, 工厂方法都能减小对源代码的修改.
2. 当有平行类结构的时候, 工厂方法一般很受欢迎.
| Parallel Class Hierarchies When you have two set of classes that mirror each others structures.Examples occur all over the place in code, typically when you have a catalog of items, and you then have instances of those items used in specific situations. The two class hierarchies are typically Homomorphic, that is they share the same structure.For example, I have a blueprint for a widget that is made up of a gadget connected to a sprocket. I then make one. I now have a real widget, and in that widget my actual gadget is connected to a real sprocket. Not only are the parts mirrored, but the relationships are as well.I could say this a bit more formally: Suppose I have a hierarchy, C, of two classes x and y that have a function, f, such that f(x)=y. Now another parallel hierarchy, C', with two classes x' and y' is Homomorphic if it has a function, f', such that f'(x')=y'.I have a sneaking suspicion that this could all be said very elegantly in CategoryTheory, but I'm not sure how to formulate it.DanielPoon |
4. Builder ( 构建者模式 )
关键:
Builder 只关心Part 的构建, 不关心 Part 的组合.
理解:
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。 创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式;
Builder 模式是为了更灵活的实现这个公式:
Product = n1*Part1 + n2*Part2 + ... + nm*Partm( 这里 m 一般是个固定的数, 即 AbstractBuilder 内的方法数是固定的, 又即AbstractBuilder 接口是相对固定的 ).
Product 的改变取决于三方面: 一是 [ n1, n2, ... nm ] 参数取值不同; 二是 [ Part1, Part2, ... , Partm ] 顺序不同; 三是 PartX 本身的实现不同.
前两个不同在 Director中实现. 第三个不同通过构建新的 ConcreteBuilder 来实现.
| Builder核心思想: 将一个“复杂对象的构建算法”与它的“部件及组装方式”分离,使得构件算法和组装方式可以独立应对变化;复用同样的构建算法可以创建不同的表示,不同的构建过程可以复用相同的部件组装方式。 抽象的Builder类,为导向者可能要求创建的每一个构件(Part)定义一个操作(接口)。这些操作缺省情况下什么都不做。一个ConcreteBuilder类对它所感兴趣的构建重定义这些操作。每个ConcreteBuilder包含了创建和装配一个特定产品的所有代码(注意:ConcreteBuilder只是提供了使用部件装配产品的操作接口,但不提供具体的装配算法,装配算法在导向器[Director]中定义)。这些代码只需要写一次;然后不同的Director可以复用它,以在相同部件集合的基础上构建不同的Product。 引自: http://www.cnblogs.com/happyhippy/archive/2010/09/01/1814287.html |
5. Singleton ( 单例模式 )
关键:
全局访问, 唯一实例
理解:
此模式相对简单, 略





浙公网安备 33010602011771号