内部有一个数组,所有的append、insert都是对这个数组进行操作,最终返回一个字符串(产品)。
public class AbstractBasePackage {
protected MobilePackage mp;
public AbstractBasePackage(){
this.mp = new MobilePackage();
}
}
/**
* 手机套餐,三个独立不相干的模块
* @author 熊诗言
*
*/
public class MobilePackage {
private float money;
private int shortInfo;
private String music;
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
public int getShortInfo() {
return shortInfo;
}
public void setShortInfo(int shortInfo) {
this.shortInfo = shortInfo;
}
public String getMusic() {
return music;
}
public void setMusic(String music) {
this.music = music;
}
}
创建者接口,提供一个总的方法提供对象
public interface IMobileBuilder {
public void buildMoney();
public void buildShortInfo();
public void buildMuisc();
public MobilePackage getMobilePackage();
}
具体建造者1
public class MobileBuilderImp1 extends AbstractBasePackage implements IMobileBuilder {
@Override
public void buildMoney() {
this.mp.setMoney(20);
}
@Override
public void buildMuisc() {
this.mp.setShortInfo(400);
}
@Override
public void buildShortInfo() {
this.mp.setMusic("天使");
}
@Override
public MobilePackage getMobilePackage() {
return this.mp;
}
}
具体建造者2
public class MobileBuilderImp2 extends AbstractBasePackage implements IMobileBuilder {
@Override
public void buildMoney() {
this.mp.setMoney(30);
}
@Override
public void buildMuisc() {
this.mp.setShortInfo(600);
}
@Override
public void buildShortInfo() {
this.mp.setMusic("大海");
}
@Override
public MobilePackage getMobilePackage() {
return this.mp;
}
}
总导演
public class MobileDirector {
public MobilePackage buildPackage(IMobileBuilder mb){
if(mb!=null){
mb.buildMoney();
mb.buildMuisc();
mb.buildShortInfo();
return mb.getMobilePackage();
}
return null;
}
}
测试
public class MainApp {
public static void main(String[] args) {
MobileDirector md = new MobileDirector();
MobileBuilderImp1 mb1 = new MobileBuilderImp1();
MobileBuilderImp2 mb2 = new MobileBuilderImp2();
printMessage(md.buildPackage(mb1));
printMessage(md.buildPackage(mb2));
}
public static void printMessage(MobilePackage mp){
System.out.println("话费:"+mp.getMoney()+" 短信:"+mp.getShortInfo()+" 彩信:"+mp.getMusic());
}
}