The intent of the builder Pattern is to separate the construction of complex object from its representation,
so that the same construction process can create different representation. Adding a new implementation
(i.e adding a new builder) becomes easier, the object construction process becomes indepedent of the components that make up the object. This provides more control over the object construction process.
照书上的抄一段,Builder pattern 的目的是为了将一个复杂的对象的构造和表现分开, 同样的构造过程可以
生成不同的表现。 增加新的实现如增加一个builder 很容易,对象构造过程和对象的组成都是独立的,
对于对象构造能有更佳控制。
Builder:
Specifies an abstract interface for creating parts of a product object.
ConcreteBuilder:
Construct and assembles part of the product by implementing the Builder interface.
Defines and keeps track of the representation it creates.
Provides an interface for retrieving the product.
Director:
Constructs an object using the Builder interface
Product:
Represents the complex object under construction , ConcreteBuilder builds the product's
internal representation and defines the process by which it's assembled.
Include classes that define the constituent parts, including interfaces for assembling the parts into the final result.
代码:
另外一种形式的Builder pattern.
-
package builderpattern;
-
-
class Cake{
-
private final double sugar;
-
private final double butter;
-
private final double milk;
-
private final int cherry;
-
-
public static class CakeBuilder{
-
private double sugar;
-
private double butter;
-
private double milk;
-
private int cherry;
-
-
//Builder methods for setting property
-
public CakeBuilder sugar(double cup){
-
this.sugar = cup;
-
return this;
-
}
-
-
public CakeBuilder butter(double cup){
-
this.butter = cup;
-
return this;
-
}
-
-
public CakeBuilder milk(double cup){
-
this.milk = cup;
-
return this;
-
}
-
-
public CakeBuilder cherry(int number){
-
this.cherry = number;
-
return this;
-
}
-
-
//return fully build object
-
public Cake build(){
-
return new Cake(this);
-
}
-
-
}
-
-
//private constructor to enforce object creation through builder
-
private Cake(CakeBuilder builder){
-
this.sugar = builder.sugar;
-
this.butter = builder.butter;
-
this.milk = builder.milk;
-
this.cherry = builder.cherry;
-
}
-
-
@Override
-
public String toString(){
-
return "Cake [ sugar="+ sugar +", butter="+butter +",milk="+milk+",cherry="+cherry
-
+"]";
-
}
-
}
-
-
-
public class BuildPatternDemo {
-
public static void main(String[] args){
-
//Creating object using Builder pattern in java
-
Cake WhiteCake= new Cake.CakeBuilder().sugar(1).butter(0.5).milk(0.5).cherry(10).build();
-
System.out.println(WhiteCake);
-
-
Cake DietCake = new Cake.CakeBuilder().build();
-
System.out.println(DietCake);
-
}
-
}
阅读(485) | 评论(0) | 转发(0) |