建立型模式是用來建立對象的模式,抽象了實例化的過程,封裝了建立邏輯
1. 將系統所使用的具體類的信息封裝起來
2. 隱藏了類的實例是如何被建立和組織的
|
考慮下面的這種場景
有水果類(抽象類、接口)Fruit用於描述水果
另有具體的水果(實現類)蘋果Apple 橘子Orange
有一個簡單的水果店SimpleFruitFactory 可以銷售提供全部的水果
|
package simpleFactory; /** * Created by noteless on 2018/10/9. * Description: */ public interface Fruit { String description(); }
package simpleFactory; /** * Created by noteless on 2018/10/9. * Description: */ public class Apple implements Fruit { @Override public String description() { return "apple"; } }
package simpleFactory; /** * Created by noteless on 2018/10/9. * Description: */ public class Orange implements Fruit { @Override public String description() { return "Orange"; } }
package simpleFactory; /** * Created by noteless on 2018/10/9. * Description: */ public enum FruitType { APPLE, ORANGE }
package simpleFactory; /** * Created by noteless on 2018/10/9. * Description: */ public class SimpleFruitFactory { public static Fruit create(FruitType fruitType){ if(fruitType.equals(FruitType.APPLE)){ return new Apple(); }else if(fruitType.equals(FruitType.ORANGE)){ return new Orange(); } return null; } }