赞
踩
概要: 创建者模式又叫建造者模式,是将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
创建者模式隐藏了复杂对象的创建过程,它把复杂对象的创建过程加以抽象,通过子类继承或者重载的方式,动态的创建具有复合属性的对象。
①使用建造者模式可以使客户端不必知道产品内部组成的细节。
②具体的建造者类之间是相互独立的,这有利于系统的扩展。
③具体的建造者相互独立,因此可以对建造的过程逐步细化,而不会对其他模块产生任何影响。
描述: 加入我们现在要制造一辆汽车,需要很复杂的过程,我们现在将这些过程抽取出来,构建者 创建一个汽车对象。
public class Car { private String name; private String color; private String weight; private String price; private String fadongji; private String luntai; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public void setFadongji(String fadongqi) { this.fadongji = fadongqi; } public String getFadongji() { return fadongji; } public void setLunTai(String luntai) { this.luntai = luntai; } public String getLuntai() { return luntai; } @Override public String toString() { return "Car{" + "name='" + name + '\'' + ", color='" + color + '\'' + ", weight='" + weight + '\'' + ", price='" + price + '\'' + ", fadongji='" + fadongji + '\'' + ", luntai='" + luntai + '\'' + '}'; } }
public interface ICarBuilder {
void setName(String name);
void setColor(String color);
void setPrice(String price);
void setFadongji(String fadongji);
void setLuntai(String luntai);
void setWeight(String weight);
Car builderCar();
}
public class Builder implements ICarBuilder { private Car car; public Builder() { this.car = new Car(); } @Override public void setName(String name) { car.setName(name); } @Override public void setColor(String color) { car.setColor(color); } @Override public void setPrice(String price) { car.setPrice(price); } @Override public void setFadongji(String fadongji) { car.setFadongji(fadongji); } @Override public void setLuntai(String luntai) { car.setLunTai(luntai); } @Override public void setWeight(String weight) { car.setWeight(weight); } @Override public Car builderCar() { return car; } }
public class Director {
public Car constractorCar(ICarBuilder iCarBuilder){
iCarBuilder.setName("奔驰");
iCarBuilder.setColor("红色");
iCarBuilder.setFadongji("te4s发动机");
iCarBuilder.setLuntai("bai轮胎");
iCarBuilder.setPrice("1000");
iCarBuilder.setWeight("40KG");
Car car = iCarBuilder.builderCar();
return car;
}
}
public class Test {
public static void main(String[] args) {
ICarBuilder iCarBuilder = new Builder();
Director director = new Director();
Car car = director.constractorCar(iCarBuilder);
System.out.println(car);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。