标签:
设计模式
建造者模式
建造者模式将复杂对象的创建与表示分离, 使得同样的构建过程可以创建不同的表示. 客户端通过指导者获得最终产品, 指导者通过建造者构造具体产品, 最终的产品通过建造者返回给指导者.
设计原则
Java JDK中的建造者模式
建造者模式和抽象工厂模式的区别
建造者模式的使用场合
实现代码
//手机套餐 public class MobilePackage03 { 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 IMobileBuilder03 { public void buildMoney(); public void buildShortInfo(); public void buildMusic(); public MobilePackage03 getMobilePackage(); }
//抽象建造者 public abstract class AbstractBasePackage03 { protected MobilePackage03 mobilePackage03; public AbstractBasePackage03() { this.mobilePackage03 = new MobilePackage03(); } }
//具体的建造者 public class MobileBuilderImp1103 extends AbstractBasePackage03 implements IMobileBuilder03 { public void buildMoney() { this.mobilePackage03.setMoney(11f); } public void buildShortInfo() { this.mobilePackage03.setShortInfo(100); } public void buildMusic() { this.mobilePackage03.setMusic("1103"); } public MobilePackage03 getMobilePackage() { return this.mobilePackage03; } }
//具体的建造者 public class MobileBuilderImp2203 extends AbstractBasePackage03 implements IMobileBuilder03 { public void buildMoney() { this.mobilePackage03.setMoney(20f); } public void buildShortInfo() { this.mobilePackage03.setShortInfo(200); } public void buildMusic() { this.mobilePackage03.setMusic("2203"); } public MobilePackage03 getMobilePackage() { return this.mobilePackage03; } }
//手机套餐指导者 public class MobileDirector03 { public MobilePackage03 createMobilePackage03(IMobileBuilder03 builder03) { if(null != builder03) { builder03.buildMoney(); builder03.buildShortInfo(); builder03.buildMusic(); return builder03.getMobilePackage(); } return null; } }
//客户端 public class MobileMain { public static void main(String[] args) { MobileDirector03 director03 = new MobileDirector03(); MobileBuilderImp1103 imp1103 = new MobileBuilderImp1103(); MobileBuilderImp2203 imp2203 = new MobileBuilderImp2203(); printMessage(director03.createMobilePackage03(imp1103)); printMessage(director03.createMobilePackage03(imp2203)); } public static void printMessage(MobilePackage03 package03) { System.out.println("---话费: " + package03.getMoney() + "\t 短信: " + package03.getShortInfo() + "\t 彩铃: " + package03.getMusic()); } }
标签:
原文地址:http://www.cnblogs.com/jin12/p/5567747.html