设计模式note2:简单工厂模式(非23种之一)
程序员文章站
2024-01-20 12:57:10
...
设计:
需求:披萨店后厨做披萨,披萨店卖披萨,消费者买披萨。
通过简单工厂类,将所有的创建(做)披萨对象交给SimpleFactroy
1.pizza抽象类
//设计抽象类:pizza后厨做披萨
abstract class Pizza{
protected String name;
//准备原材料:不同披萨不同
public abstract void prepare();
//1.切
public void cut(){
System.out.println("切蛋糕!");
}
//2.烘烤
public void bake(){
System.out.println("烘烤蛋糕!");
}
//3.打包
public void box(){
System.out.println("打包!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.实现类,两种披萨
//后厨制作GreekPizza
class GreekPizza extends Pizza {
@Override
public void prepare() {
System.out.println("准备希腊蛋糕GreekPizza的原料!");
}
public GreekPizza() {
name = "希腊披萨";
prepare();
cut();
bake();
box();
}
}
//后厨制作GreekPizza
class ChessPizza extends Pizza {
@Override
public void prepare() {
System.out.println("准备起司披萨ChessPizza的原料!");
}
public ChessPizza(){
name = "起司披萨";
prepare();
cut();
bake();
box();
}
}
3.披萨商店:订购披萨业务
//订购披萨:披萨商店销售披萨
class OrderPizza{
String pizzaType;
//客人要指定需要的披萨
OrderPizza(String pizzaType){
this.pizzaType = pizzaType;
}
//通过简单工厂类来创建相关披萨
PizzaSimpleFactory pizzaSimpleFactory = new PizzaSimpleFactory();
public Pizza getPizza(){
if ("chessPizza".equals(pizzaType)){
return pizzaSimpleFactory.getChessPizza();
}else {
return pizzaSimpleFactory.getGreekPizza();
}
}
}
4.做披萨的类
//简单工厂类:把所有的创建都放在这里进行
public class PizzaSimpleFactory {
public ChessPizza getChessPizza() {
return new ChessPizza();
}
public GreekPizza getGreekPizza(){
return new GreekPizza();
}
}
5.消费者来买披萨
public class Consumer {
public static void main(String[] args) {
OrderPizza op = new OrderPizza("chessPizza");
Pizza pizza = op.getPizza();
System.out.println("买到了一个"+pizza.name);
}
}
上一篇: jquery变量赋值问题