码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式3-简单工厂模式

时间:2019-04-17 16:31:20      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:system   xtend   ack   new   package   pre   ext   sys   []   

package DesignPattern;

public class SimpleFactoryPattern {
    public static class Pizza{
        public String type="Pizza";
        public void prepare(){}
        public void bake(){}
        public void cut(){}
        public void box(){}
    }

    public static class CheesePizza extends Pizza{
        CheesePizza(){
            this.type="cheesePizza";
        }
    }

    public static class PeperonPizza extends Pizza{
        PeperonPizza(){
            this.type="peperonPizza";
        }
    }

    public static class PizzaStore{
        SimpleFactory factory;
        public PizzaStore(SimpleFactory factory){
            this.factory=factory;
        }
        public Pizza orderPizza(String type){
            Pizza pizza=SimpleFactory.createPizza(type);
            pizza.prepare();
            pizza.bake();
            pizza.cut();
            pizza.box();
            return pizza;
        }
    }

    public static class SimpleFactory{
        public static Pizza createPizza(String type){
            Pizza pizza = null;
            if (type.equals("cheese")){
                pizza= new CheesePizza();
            }
            else if(type.equals("pepperoni")){
                pizza= new PeperonPizza();
            }
            return pizza;
        }
    }
    //简单工厂更像是一种编码风格,只是简单的将复杂的创建方法独立出来放在简单工厂里
    //适用于复杂的创建过程,一致的加工流程
    public static void main(String[] args) {
        SimpleFactory simpleFactory = new SimpleFactory();
        PizzaStore pizzaStore = new PizzaStore(simpleFactory);
        Pizza cheesePizza = pizzaStore.orderPizza("cheese");
        System.out.println(cheesePizza.type);
    }
}

设计模式3-简单工厂模式

标签:system   xtend   ack   new   package   pre   ext   sys   []   

原文地址:https://www.cnblogs.com/zhouyu0-0/p/10724337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!