认识
抽象工厂模式的结构:抽象工厂、具体工厂、抽象产品、具体产品
伪代码
//抽象产品:动物类
interface Animal {
public void show();
}
//抽象产品:植物类
interface Plant {
public void show();
}
//具体产品:马类
class Horse implements Animal {
public Horse() {}
public void show() {
syso "具体的马";
}
}
//具体产品:牛类
class Cattle implements Animal {
public Cattle() {}
public void show() {
syso "具体的牛";
}
}
//具体产品:水果类
class Fruitage implements Plant {
public Fruitage() {}
public void show() {
syso "具体的水果";
}
}
//具体产品:蔬菜类
class Vegetables implements Plant {
public Vegetables() {}
public void show() {
syso "具体的蔬菜";
}
}
//抽象工厂:农场类
interface Farm {
public Animal newAnimal();
public Plant newPlant();
}
//具体工厂:村东农场类
class CDfarm implements Farm {
public Animal newAnimal() {
System.out.println("新牛出生!");
return new Cattle();
}
public Plant newPlant() {
System.out.println("蔬菜长成!");
return new Vegetables();
}
}
//具体工厂:村西农场类
class CXfarm implements Farm {
public Animal newAnimal() {
System.out.println("新马出生!");
return new Horse();
}
public Plant newPlant() {
System.out.println("水果长成!");
return new Fruitage();
}
}
//外部调用
main
//定义两个工厂(两个农场)
Farm f1 = new CDfarm();
Farm f2 = new CXfarm();
//村东的牛
Animal a1 = f1.newAnimal();
//村西的马
Animal a2 = f2.newAnimal();
//村东的蔬菜
Plant p1 = f1.newPlant();
//村西的水果
Plant p2 = f2.newFruitage();
a1.show();
a2.show();
f1.show();
f2.show();