23种设计模式上篇

创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。

简单工厂模式

在GOF23种设计模式中,简单工厂模式并不包含在其中。他是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特例

public abstract class Coffee {

    /**
     * 获取coffee名称
     * @return
     */
    public abstract String getName();
    
}

public class Americano extends Coffee {

    @Override
    public String getName() {
        return "美式咖啡";
    }

}

public class Cappuccino extends Coffee {

    @Override
    public String getName() {
        return "卡布奇诺";
    }

}

public class Latte extends Coffee {

    @Override
    public String getName() {
        return "拿铁";
    }

}

public class SimpleFactory {
    
    /**
     * 通过类型获取Coffee实例对象
     * @param type 咖啡类型
     * @return
     */
    public static Coffee createInstance(String type){
        if("americano".equals(type)){
            return new Americano();
        }else if("cappuccino".equals(type)){
            return new Cappuccino();
        }else if("latte".equals(type)){
            return new Latte();
        }else{
            throw new RuntimeException("type["+type+"]类型不可识别,没有匹配到可实例化的对象!");
        }
    }
    
    public static void main(String[] args) {
        Coffee latte = SimpleFactory.createInstance("latte");
        System.out.println("创建的咖啡实例为:" + latte.getName());
        Coffee cappuccino = SimpleFactory.createInstance("cappuccino");
        System.out.println("创建的咖啡实例为:" + cappuccino.getName());
    }

}

猜你喜欢

转载自www.cnblogs.com/moris5013/p/11549210.html
今日推荐