星期五, 八月 22, 2008

Learning Today: 设计模式 (2) -- Abstract Factory, Builder

Abstract Factory
**Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
**Applicability
Use the Abstract Factory pattern when:
  • a system should be independent of how its products are created, composed, and represented.
  • a system should be configured with one of multiple families of products. 
  • a family of related product objects is designed to be used together, and you need to enforce this constraint.
  • you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
**Structure:
Client, Abstract Factory, Concrete Factory, Abstract Product, Concrete Product


Builder

**Intent:Separate the construction of a complex object from its representation so that the same construction process can create different representations.
**Applicability
Use the Builder pattern when:
  • the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.
  • the construction process must allow different representations for the object that's constructed.
**Structure:
Director, Builder, Concrete Builder, Product

相同点

Abstract Factory和Builder都实现了product和implementation的分离

不同点
Builder有一个director,product由director负责。director来指导builder, step by step生产product;而Abstract Factory中,client跟Abstract Factory以及Abstract Product都有联系。
对于Builder,product的implementation不可见;对于Abstract Factory,product的implementation作为接口(抽象方法可见,具体方法不可见)。如:[2]中的cook调用setPizzaBuilder,然后constructPizza,对于PizzaBuilder中的方法不可见。[1]中client可以调用factory.createButton。比如,factory中实现了A,B,C三种方法,那么client可以手动指定A,B,C三种方法的顺序。而对于Builder,顺序是写在每一个Concrete Builder中的,你只可以选用哪一个Concrete Builder,而不能手动来指定Builder中调用方法的顺序。

references:
1.http://en.wikipedia.org/wiki/Abstract_factory_pattern
2.http://en.wikipedia.org/wiki/Builder_pattern
3.GoF: Design Pattern

没有评论: