学习设计模式的日常Demo
工厂方法模式
工厂方法模式介绍
代码实现:
abstract class OrderPizza {
// 定义一个抽象方法,让各个工厂自己实现
abstract Pizza createPizza(String orderType);
public void buy() {
String orderType = ""; // 用户输入的
Pizza pizza = null;
do {
orderType = getType();
pizza = createPizza(orderType); // 抽象方法,由工厂子类实现
//输出pizza
if (pizza != null) { // 订购成功
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
} else {
System.out.println("订购披萨失败");
break;
}
} while (true);
}
// 写一个方法,可以获取客户输入的披萨种类
private String getType() {
try {
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza 种类:");
String str = strin.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
// 伦敦订单只准备伦敦的口味
public class LDOrderPizza extends OrderPizza {
@Override
Pizza createPizza(String orderType) {
Pizza pizza = null;
if (orderType.equals("chess")) {
pizza = new LDCheesePizza();
} else if (orderType.equals("pepper")) {
pizza = new LDPepperPizza();
}
return pizza;
}
}
// 北京订单只准备北京的口味
public class BJOrderPizza extends OrderPizza {
@Override
Pizza createPizza(String orderType) {
Pizza pizza = null;
if (orderType.equals("chess")) {
pizza = new BJCheesePizza();
} else if (orderType.equals("pepper")) {
pizza = new BJPepperPizza();
}
return pizza;
}
}
// 定义抽象Pizza
public abstract class Pizza {
protected String name; //名字
//准备原材料, 不同的披萨不一样,因此,我们做成抽象方法
public abstract void prepare();
public void bake() {
System.out.println(name + " baking;");
}
public void cut() {
System.out.println(name + " cutting;");
}
//打包
public void box() {
System.out.println(name + " boxing;");
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
// 定义具体的各个pizza类
public class BJCheesePizza extends Pizza {
@Override
public void prepare() {
// TODO Auto-generated method stub
setName("北京奶酪pizza");
System.out.println("准备*北京奶酪*原材料");
}
}
public class BJPepperPizza extends Pizza {
@Override
public void prepare() {
// TODO Auto-generated method stub
setName("北京胡椒pizza");
System.out.println("准备*北京胡椒*原材料");
}
}
public class LDCheesePizza extends Pizza {
@Override
public void prepare() {
// TODO Auto-generated method stub
setName("伦敦奶酪pizza");
System.out.println("准备*伦敦奶酪*原材料");
}
}
public class LDPepperPizza extends Pizza {
@Override
public void prepare() {
// TODO Auto-generated method stub
setName("伦敦胡椒pizza");
System.out.println("准备*伦敦胡椒*原材料");
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = "";
boolean flag = true;
while (flag) {
System.out.println("欢迎来到pizza点单系统!请按照提示输入!");
System.out.println("北京---->北京地区披萨");
System.out.println("伦敦---->伦敦地区披萨");
System.out.println("quit--->退出");
s = sc.nextLine();
switch (s) {
case "北京":
new BJOrderPizza().buy();
break;
case "伦敦":
new LDOrderPizza().buy();
break;
case "quit":
flag = false;
break;
default:
break;
}
}
}
}
GitHub:设计模式源代码
来源:CSDN
作者:咣咣咣.
链接:https://blog.csdn.net/qq_44779506/article/details/104795935