抽象工厂模式

抽象工厂模式:将一组具有相同主题的单独的工厂封装起来,抽象工厂可以理解为工厂的工厂。抽象工厂模式比工厂模式具有更高的抽象程度,更广泛的适用性。
工厂方法模式:针对的是 一个产品等级结构。
抽象工厂模式:针对 多个产品等级结构。
// 抽象食物
interface Food {
public String getFoodName();
}

// 抽象餐具
interface TableWare {
public String getToolName();
}

// 抽象工厂
interface KitchenFactory {
public Food getFood();
public TableWare getTableWare();
}

//具体食物 Apple 的定义如下
class Apple implements Food{
public String getFoodName() {
return "apple";
}
}

//具体餐具 Knife 的定义如下
class Knife implements TableWare {
public String getToolName() {
return "knife";
}
}

// 以具体工厂 AKitchen 为例
class AKitchen implements KitchenFactory {

public Food getFood() {
return new Apple();
}

public TableWare getTableWare() {
return new Knife();
}
}

// 吃货要开吃了
public class Foodaholic {

public void eat(KitchenFactory k) {
System.out.println("A foodaholic is eating "+ k.getFood().getFoodName()
+ " with " + k.getTableWare().getToolName() );
}

public static void main(String[] args) {
Foodaholic fh = new Foodaholic();
KitchenFactory kf = new AKitchen();
fh.eat(kf);
}
}

posted @ 2018-02-02 18:59  寒枝将息  阅读(123)  评论(0编辑  收藏  举报