工廠模式分爲:簡單工廠模式,工廠方法模式,抽象工廠模式java
簡單工廠模式分離產品的建立者和消費者,有利於軟件系統結構的優化;可是因爲一切邏輯都集中在一個工廠類中,致使了沒有很高的內聚性,同時也違背了「開放封閉原則」。另外,簡單工廠模式的方法通常都是靜態的,而靜態工廠方法是沒法讓子類繼承的,所以,簡單工廠模式沒法造成基於基類的繼承樹結構。ide
示例代碼:測試
public class FoodFactory { public static Food getFood(String type){ try { if("MC".equals(type.toUpperCase())){ return McChicken.class.newInstance(); }else if("CHIP".equals(type.toUpperCase())){ return Chips.class.newInstance(); }else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } public static Food getFood(Class<? extends Food> foodClass){ try { if(McChicken.class.equals(foodClass)){ return McChicken.class.newInstance(); }else if(Chips.class.equals(foodClass)){ return Chips.class.newInstance(); }else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } }
簡單工廠模式嚴重違背了「開閉原則」,難以拓展,由此產生了工廠方法模式。工廠方法(Factory Method)模式的意義是定義一個建立產品對象的工廠接口,將實際建立工做推遲到子類當中。核心工廠類再也不負責產品的建立,這樣核心類成爲一個抽象工廠角色,僅負責具體工廠子類必須實現的接口,這樣進一步抽象化的好處是使得工廠方法模式能夠使系統在不修改具體工廠角色的狀況下引進新的產品。優化
示例代碼:spa
定義接口:code
public interface FactoryBMW { BMW createBMW(); }
實現接口:對象
public class FactoryBMW320 implements FactoryBMW { @Override public BMW createBMW() { return new BMW320(); } } public class FactoryBMW523 implements FactoryBMW { @Override public BMW createBMW() { return new BMW523(); } }
定義實例:繼承
public class BMW { public BMW(){ } } public class BMW320 extends BMW { public BMW320(){ System.out.println("320"); } } public class BMW523 extends BMW { public BMW523(){ System.out.println("523"); } }
測試方法:接口
public class Test { public static void main(String[] args) { FactoryBMW factoryBMW = new FactoryBMW320(); factoryBMW.createBMW(); } }
定義工廠:ip
public interface AbstractFactory { Engine createEngine(); Aircondition createAircondition(); } public class FactoryBMW320 implements AbstractFactory { @Override public Engine createEngine() { return new EngineA(); } @Override public Aircondition createAircondition() { return new AirconditionA(); } } public class FactoryBMW523 implements AbstractFactory { @Override public Engine createEngine() { return new EngineB(); } @Override public Aircondition createAircondition() { return new AirconditionB(); } }
定義組件:
public interface Aircondition { } public class AirconditionA implements Aircondition { public AirconditionA(){ System.out.println(AirconditionA.class.getSimpleName()); } } public class AirconditionB implements Aircondition { public AirconditionB(){ System.out.println(AirconditionB.class.getSimpleName()); } } public interface Engine { } public class EngineA implements Engine { public EngineA(){ System.out.println(EngineA.class.getSimpleName()); } } public class EngineB implements Engine { public EngineB(){ System.out.println(EngineB.class.getSimpleName()); } }
測試方法:
public class Test { public static void main(String[] args) { AbstractFactory factory = new FactoryBMW320(); factory.createEngine(); factory.createAircondition(); } }