package Create.a.SimpleFactory;
//業務接口 public interface Salary { void calcSalary(); }
package Create.a.SimpleFactory;
//業務實現類 public class HeBeiSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("開始計算河北子公司的薪資!"); } }
package Create.a.SimpleFactory; //業務實現類 public class GuangDongSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("開始計算廣東子公司的薪資!"); } }
package Create.a.SimpleFactory; //工廠類 public class SimpleFactory { public static Salary createSalary(String name){ if(name.equals("HeBei")){ return new HeBeiSalary(); } if(name.equals("GD")){ return new GuangDongSalary(); } return null; } } 若是後期需求須要變動時,即須要變更if條件內容
package Create.a.SimpleFactory; //業務調用類 public class Client { public static void main(String[] args) { Salary sa = SimpleFactory.createSalary("HeBei"); sa.calcSalary(); sa = SimpleFactory.createSalary("GD"); sa.calcSalary(); } }
優勢:在簡單工廠模式中,客戶端再也不負責對象的建立,而是把這個任務丟給工廠類,客戶端只負責對對象實例的調用java
缺點:沒法繼承,變動需求時須要不斷修改工廠類的判斷邏輯ide