您的位置:首页 > 编程语言 > Java开发

设计模式--创建模式--建造模式--java

2013-01-15 17:36 826 查看

intent

•Separate the construction of a complex object from itsrepresentation so that the same construction process can create differentrepresentations .
•将构建和表示分离,使同样的构建过程可以创建不同的表示。

UML

Applicability

•the algorithm for creating a complex object should beindependent of the parts that make up the object and how they're assembled.
•创建复杂的对象的算法应该独立于组装部分和他们如何装配的。
•the construction process must allow differentrepresentations for the object that's constructed.
•构造的过程要求创建出来的对象有不同的表示。

Consequences

•Itlets you vary a product's internal representation
•使得产品内部表示可变。
•Itisolates code for construction and representation.
•分离构建代码和表示代码。
•Itgives you finer control over the construction process.
•使得构建过程更出色,更灵活。

example-StringBuilder

/**
* 在使用StringBuilder端,实际上具有Client和Director角色。
* @author changsheng
*
*/
public class ClientDirector {

public static void main(String[] args) {

StringBuilder sb = new StringBuilder();

/**
* Director可以随意指导Builder来构造出不同的表示。
*/
sb.append(8);
sb.append(27);
sb.append("chang");
sb.append("sheng");
sb.append(2012);

/**
* 等价于Builder的getResult方法。
*/
String result = sb.toString();

System.out.println(result);

}

}


在StringBuilder中构造算法以及组装过程都被封装起来了,由Director去指导要构造出什么样的产品。建议看下StringBuilder源码,更能深入理解下BuilderPattern

所有实现此接口java.lang.Appendable,的都使用了BuilderPattern。


http://www.cnitblog.com/sugar/archive/2006/02/22/6808.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息