抽象工厂模式是所有形态的工厂模式中最为抽象和最其一般性的。抽象工厂模式可以向客户端提供一个接口,使得客户端在不必指定产品的具体类型的情况下,能够创建多个产品族的产品对象。1.抽象工厂(Creator)角色抽象工厂模式的核心,包含对多个产品结构的声明,任何工厂类都必须实现这个接口。2.具体工厂( Concrete Creator)角色具体工厂类是抽象工厂的一个实现,负责实例化某个产品族中的产品对象。3.抽象(Product)角色 抽象模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。4.具体产品(Concrete Product)角色抽象模式所创建的具体实例对象
看代码吧:
1、抽象产品1:public abstract class Boy { abstract void run();}
2、抽象产品2:
public abstract class Girl { abstract void makeUp();}
3、具体产品1:
public class BlackBoy extends Boy { @Override void run() { System.out.println("this is BlackBoy run!"); }}
4、具体产品2:
public class YellowBoy extends Boy { @Override void run() { System.out.println("this is YellowBoy run!"); }}
6、具体产品3:
public class BlackGirl extends Girl { @Override void makeUp() { System.out.println("this is BlackGirl makeup!"); }}
7、具体产品4:
public class YellowGirl extends Girl { @Override void makeUp() { System.out.println("this is YellowGirl is makeup!"); }}
8、抽象工厂:
public abstract class PeopleFactory { abstract Boy createBoy(); abstract Girl createGirl();}
9、具体工厂1:
public class BlackPeopleFacotry extends PeopleFactory { @Override Boy createBoy() { return new BlackBoy(); } @Override Girl createGirl() { return new BlackGirl(); }}
10、具体工厂2:
public class YellowPeopleFacotry extends PeopleFactory { @Override Boy createBoy() { return new YellowBoy(); } @Override Girl createGirl() { return new YellowGirl(); }}
11、测试类:
public class TestClass { public static void main(String[] args) { PeopleFactory factory = new BlackPeopleFacotry(); Boy boy = factory.createBoy(); Girl girl = factory.createGirl(); boy.run(); girl.makeUp(); factory = new YellowPeopleFacotry(); boy = factory.createBoy(); girl = factory.createGirl(); boy.run(); girl.makeUp(); }}
输出 :
this is BlackBoy run!this is BlackGirl makeup!this is YellowBoy run!this is YellowGirl is makeup!