抽象工厂模式
1 基本介绍
1) 抽象工厂模式:定义了一个 interface 用于创建相关或有依赖关系的对象簇,而无需指明具体的类
2) 抽象工厂模式可以将简单工厂模式和工厂方法模式进行整合。
3) 从设计层面看,抽象工厂模式就是对简单工厂模式的改进(或者称为进一步的抽象)。
4) 将工厂抽象成两层,AbsFactory(抽象工厂) 和 具体实现的工厂子类。程序员可以根据创建对象类型使用对应的工厂子类。这样将单个的简单工厂类变成了工厂簇,更利于代码的维护和扩展。
5) 类图
2 抽象工厂模式应用实例
使用抽象工厂模式来完成披萨项目
Pizza类
package com.lin.abstractfactory; abstract class Pizza{ private String name; public void setName(String name) {
this.name = name;
} public void prepare() {
System.out.println(name + " are prepared!");
} public void bake() {
System.out.println(name + " are baked!");
} public void cut() {
System.out.println(name + " are cutted!");
} public void box() {
System.out.println(name + " are boxed!");
} } // 北京chesspizza
class BJChessPizza extends Pizza{ } // 北京greekpizza
class BJGreekPizza extends Pizza{ } //伦敦chesspizza
class LNChessPizza extends Pizza{ } //伦敦greekpizza
class LNGreekPizza extends Pizza{ }
AbstractFactory类
package com.lin.abstractfactory; interface AbstarctFactory { public abstract Pizza createPizza(String orderType); } class BJFactory implements AbstarctFactory{ @Override
public Pizza createPizza(String orderType) {
Pizza pizza = null;
if(orderType.equals("cheese")) {
pizza = new BJChessPizza();
pizza.setName("北京Cheese");
} else if(orderType.equals("greek")) {
pizza = new BJGreekPizza();
pizza.setName("北京Greek");
}
return pizza;
} } class LNFactory implements AbstarctFactory{ @Override
public Pizza createPizza(String orderType) {
Pizza pizza = null;
if(orderType.equals("cheese")) {
pizza = new LNChessPizza();
pizza.setName("伦敦Cheese");
} else if(orderType.equals("greek")) {
pizza = new LNGreekPizza();
pizza.setName("伦敦Greek");
}
return pizza;
} }
OrderPizza类
package com.lin.abstractfactory; import java.util.Scanner; public class OrderPizza { AbstarctFactory factory; public OrderPizza(AbstarctFactory factory) {
setAbsFactory(factory);
} public void setAbsFactory(AbstarctFactory factory) {
Pizza pizza = null;
String orderType = "";
this.factory = factory;
while(true) {
orderType = getType();
pizza = factory.createPizza(orderType);
if( pizza != null) {
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
} else {
System.out.println("没有这种类型!");
}
}
} public String getType() {
Scanner str = new Scanner(System.in);
System.out.println("please input the type of ordered pizza:");
String type = str.next();
return type;
}
}
PizzaStore类
package com.lin.abstractfactory; public class PizzaStore { public static void main(String[] args) {
// new OrderPizza(new BJFactory());
new OrderPizza(new LNFactory());
}
}
仅供参考,有错误还请指出!
有什么想法,评论区留言,互相指教指教。