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

java设计模式学习笔记-构建模式

2013-12-24 14:39 459 查看

该模式有4个角色:构建工具接口、构建接口实现类、构建类、产品类

1、产品

package model06.create;

public class Car{
private String engine;
private String wheel;

protected Car(String enqine, String wheel){
this.engine = engine;
this.wheel = wheel;
}

protected Car(){
}

public String getEngine(){
return engine;
}

public void setEngine(String engine){
this.engine = engine;
}

public String getWheel(){
return this.wheel;
}

public void setWheel(String wheel){
this.wheel = wheel;
}
}


2、构建者工具接口

package model06.create;

public interface Builder{
public void buildEngine() throws Exception;
public void buildWheel() throws Exception;
public Car getCar() throws Exception;
}

3、构建者工具接口的实现

package model06.create;

public class CarBuilder inplements Builder{
private String engine;
private String wheel;
public void buildEngine() throws Exception{
this.engine = "engine";
}

public void buildWheel() throws Exceptino{
this.wheel = "wheel";
}

public Car getCar() throws Exception{
return new Car(engine, wheel);
}
}

4、构建者类

package model06.create;

public class Director{
public Builder builder;
public Director(Builder builder){
this.builder = builder;
}

public void constrct() throws Exception{
if(builder == null){
throw new RuntimeException("no builder");
}
builder.buildEngine();
builder.buildWheel();
}
}

构造者模式的优缺点

优点

1:建造模式的使用使得产品的内部表象可以独立地变化。使用建造模式可以使客户端不必知道产品内部组成的细节

2:每一个Builder都相对独立,而与其他的Builder无关

3:模式所建造的最终产品更易于控制

缺点

创建者模式比较符合产品差别不大的对象的创建,如果差别很大,就会导致非常多的具体的创建者,这时候最好结合工厂方法模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息