Android设计模式解析与实战-Builder模式
2017-03-15 本文已影响4人
VegetableAD
定义
* 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
实例代码:
public class BuilderTest{
abstract class Computer{
String mBoard;
String mScreen;
String mOs;
protected Computer(){}
public void setBoard(String board){mBoard = board;}
public void setScreen(String screen){mScreen = screen;}
public abstract void setOs(String os);
public String toString(){
return "the os is " + mOs;
}
}
class MacBook extends Computer{
protected MacBook(){}
public void setOs(String os){mOs = os;};
}
abstract class Builder{
public abstract Builder builderBoard(String board);
public abstract Builder builderScreen(String screen);
public abstract Builder builderOs();
public abstract Computer create();
}
class MacBookBuilder extends Builder{
private Computer computer = new MacBook();
public Builder builderBoard(String board){
computer.setBoard(board);
return this;
}
public Builder builderScreen(String screen){
computer.setScreen(screen);
return this;
}
public Builder builderOs(){
computer.setOs("iOS");
return this;
}
public Computer create(){
return computer;
}
}
public static void main(String[] args) {
BuilderTest test = new BuilderTest();
Builder builder = test.new MacBookBuilder();
Computer com = builder.builderBoard("ha").builderScreen("dell").builderOs().create();
System.out.println(com);
}
}