建立型模式是用来建立对象的模式,抽象了实例化的过程,封装了建立逻辑
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; } }