标签:
class Computer
{
private String name=null;
private String cpu=null;
private String ddr=null;
private String hdd=null;
public void setName(String name)
{
this.name=name;
}
public void setCpu(String cpu)
{
this.cpu=cpu;
}
public void setDdr(String ddr)
{
this.ddr=ddr;
}
public void setHdd(String hdd)
{
this.hdd=hdd;
}
public void printInfo()
{
System.out.println(name+" computer profile is:"+"cpu->"+cpu+", ddr->"+ddr+", hdd->"+hdd);
}
}
abstract class Builder
{
//private Computer aComputer=new Computer();
public abstract void buildCpu();
public abstract void buildDdr();
public abstract void buildHdd();
public abstract Computer getProduct();
}
class T60Builder extends Builder
{
private Computer aComputer=null;
public T60Builder()
{
aComputer=new Computer();
aComputer.setName("T60");
}
public void buildCpu()
{
aComputer.setCpu("core duro 2.0GHZ");
}
public void buildDdr()
{
aComputer.setDdr("Kingston 1G DDR");
}
public void buildHdd()
{
aComputer.setHdd("WD 160GB DISK");
}
public Computer getProduct()
{
return aComputer;
}
}
class T61Builder extends Builder
{
private Computer aComputer=null;
public T61Builder()
{
aComputer=new Computer();
aComputer.setName("T61");
}
public void buildCpu()
{
aComputer.setCpu("core duro 2.3GHZ");
}
public void buildDdr()
{
aComputer.setDdr("Kingston 2G DDR");
}
public void buildHdd()
{
aComputer.setHdd("WD 250GB DISK");
}
public Computer getProduct()
{
return aComputer;
}
}
class WorkerDirector
{
private Builder aBuilder=null;
public void constructorComputer(Builder builder)
{
aBuilder=builder;
aBuilder.buildCpu();
aBuilder.buildDdr();
aBuilder.buildHdd();
}
}
public class BuilderPatternTest
{
public static void main(String[] args)
{
Builder aBuilder=new T60Builder();
WorkerDirector aWorkerDirector=new WorkerDirector();
aWorkerDirector.constructorComputer(aBuilder);
Computer aComputer=aBuilder.getProduct();
aComputer.printInfo();
aBuilder=new T61Builder();
aWorkerDirector.constructorComputer(aBuilder);
aComputer=aBuilder.getProduct();
aComputer.printInfo();
}
}
///////////////////////////////////////
输出结果:
T60 computer profile is:cpu->core duro 2.0GHZ, ddr->Kingston 1G DDR, hdd->WD 160GB DISK
T61 computer profile is:cpu->core duro 2.3GHZ, ddr->Kingston 2G DDR, hdd->WD 250GB DISK
java中23种设计模式之9-建造者模式(builder pattern)
标签:
原文地址:http://www.cnblogs.com/wudymand/p/4379006.html