package factory; /*为了克服简单工厂模式对修改开放的缺点,进一步改进,把工厂方法抽象化,加以延伸,使得在子类中进一步决定如何去实现pizza对象, * 本文中引入了不同地区的披萨商店可以自己定制本地风格的披萨系统,利用工厂方法设计模式对简单工厂中的方法抽象化,提升代码弹性 */ interface Pizza //抽象产品类(接口) { void makePizza(); } class NYStyleCheesePizza implements Pizza //具体产品类,它的对象就是工厂能实际制造的披萨(产品) { public void makePizza() { System.out.println("make pizza with NYcheese"); //制作纽约风格芝士披萨 } } class NYStyleBeefPizza implements Pizza { public void makePizza() { System.out.println("make pizza with NYbeef"); //制作纽约风格牛肉披萨 } } class ChicagoStyleCheesePizza implements Pizza { public void makePizza() { System.out.println("make pizza with chicagocheese"); //制作芝加哥风格芝士披萨 } } class ChicagoStyleBeefPizza implements Pizza { public void makePizza() { System.out.println("make pizza with chicagobeef"); //制作芝加哥风格牛肉披萨 } } /* class SimplePizzaFactory { public static Pizza createPizza(String type) { if(type == "cheese") { return new CheesePizza(); } else if(type == "beef") { return new BeefPizza(); } else { return null; } } }*/ //相比简单工厂,去掉了这里的工厂函数,把函数挪到了store里,然后让其抽象化,使得在子类中实现该方法,增加实例化对象的代码弹性 abstract class PizzaStore //创建者类,它定义了一个抽象的工厂方法,让子类实现此方法制造产品 { abstract Pizza createPizza(String type); //相比简单工厂,把createPizza方法从工厂移到了这里(商店),且变为抽象的方法 public final Pizza orderPizza(String type) //定义为final不可重写,因为无论是哪个区域的披萨商店都要有此流程 { Pizza pizza = createPizza(type); //该方法在此没有实现,由其子类实现,让子类做决定 pizza.makePizza(); return pizza; } } class NYPizzaStore extends PizzaStore //实现了一个具体的披萨商店类,纽约披萨商店 { public Pizza createPizza(String type) //判断并实例化披萨 { if(type == "cheese") { return new NYStyleCheesePizza(); } else if(type == "beef") { return new NYStyleBeefPizza(); } else { return null; } } } class ChicagoPizzaStore extends PizzaStore //实现了一个具体的披萨商店类,芝加哥披萨商店 { public Pizza createPizza(String type) //判断并实例化披萨 { if(type == "cheese") { return new ChicagoStyleCheesePizza(); } else if(type == "beef") { return new ChicagoStyleBeefPizza(); } else { return null; } } } public class Factory { public static void main(String[] args) { PizzaStore store = new NYPizzaStore(); //创建一个纽约披萨商店类的对象 Pizza pizza = store.orderPizza("beef"); //定制该披萨,类型选择牛肉披萨 store = new ChicagoPizzaStore(); //创建一个芝加哥商店类的对象 pizza = store.orderPizza("cheese"); //定制该披萨,类型选择芝士披萨 } }
设计模式之工厂方法模式:不同区域的pizza口味
猜你喜欢
转载自blog.csdn.net/m0_37907835/article/details/79682797
今日推荐
周排行