package Create.d.Builder; //业务接口 public interface Tax { void calcTax(); }
package Create.d.Builder; //业务接口 public interface Salary { void calcSalary(); }
package Create.d.Builder; //业务实现类 public class HeBeiTax implements Tax { @Override public void calcTax() { // TODO Auto-generated method stub System.out.println("开始计算河北子公司的税收!"); } }
package Create.d.Builder; //业务实现类 public class HeBeiSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算河北子公司的薪资!"); } }
package Create.d.Builder; //业务实现类 public class GuangDongTax implements Tax { @Override public void calcTax() { // TODO Auto-generated method stub System.out.println("开始计算广东子公司的税收!"); } }
package Create.d.Builder; //业务实现类 public class GuangDongSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算广东子公司的薪资!"); } }
package Create.d.Builder; //工厂接口 public interface Factory { Salary createSalary(); Tax createTax(); }
package Create.d.Builder; //业务实现类工厂类 public class HeBeiFactory implements Factory { @Override public Salary createSalary() { // TODO Auto-generated method stub return new HeBeiSalary(); } @Override public Tax createTax() { // TODO Auto-generated method stub return new HeBeiTax(); } }
package Create.d.Builder; //业务实现类工厂类 public class GuangDongFactory implements Factory { @Override public Salary createSalary() { // TODO Auto-generated method stub return new GuangDongSalary(); } @Override public Tax createTax() { // TODO Auto-generated method stub return new GuangDongTax(); } }
package Create.d.Builder; //创建者类 public class Builder { Factory fa; public Builder() { super(); } public Builder(Factory fa) { super(); this.fa = fa; } //封装业务实现类调用 public void build(){ Salary sa = fa.createSalary(); Tax tax = fa.createTax(); sa.calcSalary(); tax.calcTax(); } }
package Create.d.Builder; //业务调用类 public class Client { public static void main(String[] args) { Builder builder = new Builder(new HeBeiFactory()); builder.build(); builder = new Builder(new GuangDongFactory()); builder.build(); } }
优点:客户端不再负责对象的创建和组装,而是把这个任务交给具体的创建类和组装类,只负责对对象的调用。
缺点: 如果产品之间差异非常大,需要编写多个创建者类才能实现,此时应考虑使用同工厂模式一同使用,效果更好。