建造者模式
定义:
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
特点:
某产品(Product)构建过程基本一致,细节有差异;我们抽象出一个接口或抽象类(Builder)来描述其构建的各个步骤项;通过一个类(Director)指挥者来组织步骤执行的顺序即构建流程;具体的细节差异由Builder的子类来实现
示例:
本例用造车来模拟此模型:
/**
* 产品类:车所具有哪些属性
* 车标-车架-车轮-车动力-车电池
*/
public class Car {
private String mLogo;
private String mBody;
private String mWheel;
private String mEngine;
private String mBattery;
public String getLogo() {
return mLogo;
}
public void setLogo(String logo) {
mLogo = logo;
}
public String getBody() {
return mBody;
}
public void setBody(String body) {
mBody = body;
}
public String getWheel() {
return mWheel;
}
public void setWheel(String wheel) {
mWheel = wheel;
}
public String getEngine() {
return mEngine;
}
public void setEngine(String engine) {
mEngine = engine;
}
public String getBattery() {
return mBattery;
}
public void setBattery(String battery) {
mBattery = battery;
}
}
/**
* 模拟组装汽车所需的工作-步骤划分
* 具体组装由具体车型实现
*/
public interface ICarBuilder {
void addLogo();
void addWheel();
void addBody();
void addEngine();
void addBattery();
}
/**
* 汽车组装指挥者,理解为组装(构建)流程,是固定的流水作业
* 这里只是模拟汽车组装流程:车体-动力-电池-车轮-厂家Logo
* 具体的组装成MPV,SUV还是轿车则由具体的组装工(建造者)来完成
*/
public class CarDirector {
public void Construct(ICarBuilder builder) {
builder.addBody();
builder.addEngine();
builder.addBattery();
builder.addWheel();
builder.addLogo();
}
}
import android.util.Log;
public class TangCarBuilder implements ICarBuilder{
private static final String CAR_TYPE = "唐100";
private Car mCar;
public TangCarBuilder(Car car) {
mCar = car;
}
@Override
public void addLogo() {
Log.d(CAR_TYPE, "addLogo");
mCar.setLogo("唐");
}
@Override
public void addWheel() {
mCar.setWheel("大轮子");
}
@Override
public void addBody() {
mCar.setBody("SUV车型");
}
@Override
public void addEngine() {
mCar.setEngine("DM 插电混动");
}
@Override
public void addBattery() {
mCar.setBattery("电池续航100KM");
}
}
如上,调用方式:
CarDirector mDirector = new CarDirector();
//构建
mDirector.construct(new TangCarBuilder(new Car()));