码迷,mamicode.com
首页 > 编程语言 > 详细

java中23种设计模式之9-建造者模式(builder pattern)

时间:2015-03-30 20:57:15      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

 

技术分享

 

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!