设计模式4-工厂方法模式
Posted zhouyu0-0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式4-工厂方法模式相关的知识,希望对你有一定的参考价值。
package DesignPattern;
import java.util.ArrayList;
public class FactoryMethodPattern {
/*
工厂方法模式要点在于将创建方法设定为抽象方法,工厂类为抽象类
适用于不同的原料配置,自定义创建方法从而形成一类产品
将创建方法开放给子类,带来的好处,共享流程和原料,创建不同的产品
*/
public static abstract class Pizza{
String name;
String dough;
String sauce;
ArrayList<String> toppings = new ArrayList();
public void prepare(){
System.out.println("Preparing "+name);
System.out.println("Tossing dough");
System.out.println("Adding sauce...");
System.out.println("Adding toppings");
for(int i=0;i<toppings.size();i++){
System.out.println(" "+toppings.get(i));
}
}
public void bake(){
System.out.println("Bake for 25 minutes at 350");
}
public void cut(){
System.out.println("Cutting the pizza into diagonal slices");
}
public void box(){
System.out.println("Place pizza in official PizzaStore box");
}
public String name(){
return name;
}
}
//纽约风格起司披萨
public static class NYStyleCheesePizza extends Pizza{
public NYStyleCheesePizza(){
this.name="NY Style Sauce and Cheese Pizza";
this.dough="Thin Crust Dough";
this.sauce="Marinara Sauce";
toppings.add("Grated Reggiano Cheese");
}
}
//芝加哥风格起司披萨
public static class ChicagoStyleCheesePizza extends Pizza{
public ChicagoStyleCheesePizza(){
this.name="Chicago Style Deep Dish Cheese Pizza";
this.dough="Extra Thick Crust Dough";
this.sauce="Plum Tomato Sauce";
toppings.add("Shreded Mozzarella Cheese");
}
public void cut(){
System.out.println("Cuttring the pizza into square slices");
}
}
public static abstract class PizzaStore{
public Pizza orderPizza(String type){
Pizza pizza=createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
abstract Pizza createPizza(String type);
}
//纽约风格披萨店
public static class NYStylePizzaStore extends PizzaStore{
@Override
Pizza createPizza(String type) {
if(type.equals("cheese")){
return new NYStyleCheesePizza();
}//此处可添加同风格其他类型的
return null;
}
}
//芝加哥风格披萨店
public static class ChicagoPizzaStore extends PizzaStore{
@Override
Pizza createPizza(String type) {
if(type.equals("cheese")){
return new ChicagoStyleCheesePizza();
}//此处可添加同风格其他类型的
return null;
}
}
public static void main(String[] args) {
PizzaStore nyStore = new NYStylePizzaStore();
nyStore.orderPizza("cheese");
System.out.println();
PizzaStore chicagoStore = new ChicagoPizzaStore();
chicagoStore.orderPizza("cheese");
System.out.println();
}
}
以上是关于设计模式4-工厂方法模式的主要内容,如果未能解决你的问题,请参考以下文章