抽象工厂模式与工厂方法模式的最大区别就在于,工厂方法模式针对的是一个产品等级结构;而抽象工厂模式则需要面对多个产品等级结构。
产品族:是指位于不同产品等级结构中,功能相关联的产品组成的家族。
显然,每一个产品族中含有产品的数目,与产品等级结构的数目是相等的。产品的等级结构和产品族将产品按照不同的方向划分,形成一个二维的坐标系,如下图所示。
在坐标图中有四个产品族,分布于三个产品等级结构中。
在上面的坐标图中,横轴表示产品等级结构,纵轴表示产品族。可以看出,图中一共有四个产品族,分布于三个不同的产品等级结构中。只要指明一个产品所处的产品族以及它所属的等级结构,就可以唯一地确定这个产品。
这样的坐标图,叫做相图。在一个相图中,坐标轴代表抽象的自由度,相图中的两个坐标点之间的绝对距离并没有意义,有意义的是点与点的相对位置。
package abstract_factory;
public interface Animal {
public void eat();
public void sleep();
}
package abstract_factory;
public interface Person {
public void eat();
public void talk();
}
package abstract_factory;
public interface NWFactory {
public Person createPerson(String type);
public Animal createAnimal(String type);
}
package abstract_factory;
public class YanSheng implements NWFactory {
Man m = null;
Bulk b = null;
public Man createPerson(String type) {
try {
m = (Man) Class.forName("abstract_factory." + type).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return m;
}
public Bulk createAnimal(String type) {
try {
b = (Bulk) Class.forName("abstract_factory." + type).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
}
package abstract_factory;
public class YinSheng implements NWFactory {
Woman w = null;
Cow c = null;
public Woman createPerson(String type) {
try {
w = (Woman) Class.forName("abstract_factory." + type).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return w;
}
public Cow createAnimal(String type) {
try {
c = (Cow) Class.forName("abstract_factory."+type).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}
package abstract_factory;
public class Man implements Person {
public void eat() {
System.out.println("男人在吃饭!");
}
public void talk() {
System.out.println("男人在说话!");
}
}
package abstract_factory;
public class Woman implements Person {
public void eat() {
System.out.println("女人在吃饭!");
}
public void talk() {
System.out.println("女人在说话!");
}
}
package abstract_factory;
public class Bulk implements Animal {
public void eat() {
System.out.println("公牛在吃草!");
}
public void sleep() {
System.out.println("公牛在睡觉!");
}
}
package abstract_factory;
public class Cow implements Animal {
public void eat() {
System.out.println("母牛在吃草!");
}
public void sleep() {
System.out.println("母牛在睡觉!");
}
}
package abstract_factory;
public class Client{
/**
* @param args
*/
public static void main(String[] args) {
NWFactory yanSheng = new YanSheng();
NWFactory yinSheng = new YinSheng();
Person man = yanSheng.createPerson("Man");
man.eat();
man.talk();
Animal bulk = yanSheng.createAnimal("Bulk");
bulk.eat();
bulk.sleep();
Person woment = yinSheng.createPerson("Woman");
woment.eat();
woment.talk();
Animal cow = yinSheng.createAnimal("Cow");
cow.eat();
cow.sleep();
}
}