02.创建型————工厂方法模式
package Create.b.FactoryMethod; //业务接口 public interface Salary { void calcSalary(); }
package Create.b.FactoryMethod; //业务实现类 public class HeBeiSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算河北子公司的薪资!"); } }
package Create.b.FactoryMethod; //业务实现类 public class GuangDongSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算广东子公司的薪资!"); } }
package Create.b.FactoryMethod; //工厂接口 public interface Factory { Salary createSalary(); }
package Create.b.FactoryMethod; //业务实现类工厂类 public class HeBeiFactory implements Factory { @Override public Salary createSalary() { // TODO Auto-generated method stub return new HeBeiSalary(); } }
package Create.b.FactoryMethod; //业务实现类工厂类 public class GuangDongFactory implements Factory{ @Override public Salary createSalary() { // TODO Auto-generated method stub return new GuangDongSalary(); } }
package Create.b.FactoryMethod; //业务调用类 public class Client { public static void main(String[] args) { Factory fa = new HeBeiFactory(); Salary sa = fa.createSalary(); sa.calcSalary(); fa = new GuangDongFactory(); sa = fa.createSalary(); sa.calcSalary(); } }
优点:每个实现类均有对象的工厂类
缺点:如果有新的实现类则需要添加新的工厂类,添加编写代码工作量