标签:抽象工厂模式
要知道抽象模式最大的优点必须先了解什么是产品等级和产品族
public interface Human {
public void getColor();
public void talk();
public void getSex();
}public abstract class AbstractYellowHuman implements Human{
public void getColor() {
System.out.println("黄种人");
}
public void talk() {
System.out.println("汉语");
}
}public class MaleYellow extends AbstractYellowHuman {
public void getSex() {
System.out.println("黄种人男性");
}
}public class FemaleYellow extends AbstractYellowHuman {
public void getSex() {
System.out.println("黄种人女性");
}
}public interface HumanFactory {
public Human createWhiteHuman();
public Human createBlackHuman();
public Human createYellowHuman();
}public class FemaleFactory implements HumanFactory {
public Human createBlackHuman() {
return null;
}
public Human createWhiteHuman() {
return null;
}
public Human createYellowHuman() {
return new FemaleYellow();
}
}public class MaleFactory implements HumanFactory {
public Human createBlackHuman() {
return null;
}
public Human createWhiteHuman() {
return null;
}
public Human createYellowHuman() {
return new MaleYellow();
}
}public class Client {
public static void main(String[] args) {
HumanFactory factory=new MaleFactory();
MaleYellow maleYellow=(MaleYellow) factory.createYellowHuman();
maleYellow.talk();
}
}
/* Human接口
* 抽象类白种人AbstractWhiteHuman实现Human接口中俩个方法talk()和getColor(),这样就有了三种人
* 白种男人 MaleWhiteHuman 继承AbstractWhiteHuman 得到白种男人
* 白种女人 FemaleWhiteHuman 继承AbstractWhiteHuman得到白种女人
* 至于工厂就可以自己DIY了
* */适用场景
当需要创建的对象是一系列相互关联或相互依赖的产品族时,便可以使用抽象工厂模式。说的更明白一点,就是一个继承体系中,如果存在着多个等级结构(即存在着多个抽象类),并且分属各个等级结构中的实现类之间存在着一定的关联或者约束,就可以使用抽象工厂模式。假如各个等级结构中的实现类之间不存在关联或约束,则使用多个独立的工厂来对产品进行创建,则更合适一点。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:抽象工厂模式
原文地址:http://blog.csdn.net/cjvs9k/article/details/46943045