具体实现
package com.designmode.abstractfactory;
public abstract class AbstractProductA {
abstract public void introduce();
}
package com.designmode.abstractfactory;
public abstract class AbstractProductB {
abstract public void introduce();
}
package com.designmode.abstractfactory;
public class ProductA1 extends AbstractProductA{
@Override
public void introduce() {
System.out.println(" i am ProductA1");
}
}
package com.designmode.abstractfactory;
public class ProductA2 extends AbstractProductA{
@Override
public void introduce() {
System.out.println(" i am ProductA2");
}
}
package com.designmode.abstractfactory;
public class ProductB1 extends AbstractProductB{
@Override
public void introduce() {
System.out.println(" i am ProductB1");
}
}
package com.designmode.abstractfactory;
public class ProductB2 extends AbstractProductB{
@Override
public void introduce() {
System.out.println(" i am ProductB2");
}
}
package com.designmode.abstractfactory;
public abstract class AbstractFactory {
abstract AbstractProductA creatProductA();
abstract AbstractProductB creatProductB();
}
package com.designmode.abstractfactory;
public class ConcreteFacroty1 extends AbstractFactory{
@Override
AbstractProductA creatProductA() {
System.out.println("I am ConcreteFacroty1.I'm creating ProductA1.");
return new ProductA1();
}
@Override
AbstractProductB creatProductB() {
System.out.println("I am ConcreteFacroty1.I'm creating ProductB1.");
return new ProductB1();
}
}
package com.designmode.abstractfactory;
public class ConcreteFacroty2 extends AbstractFactory{
@Override
AbstractProductA creatProductA() {
System.out.println("I am ConcreteFacroty1.I'm creating ProductA2.");
return new ProductA2();
}
@Override
AbstractProductB creatProductB() {
System.out.println("I am ConcreteFacroty1.I'm creating ProductB2.");
return new ProductB2();
}
}
主函数
package com.designmode.abstractfactory;
/**
* 抽象工厂:提供一个接口,用于创建相关对象的家族(不止一个对象)。
* AbstractProductA:抽象产品A类
* AbstractProductB:抽象产品B类
* ProductA1、ProductA2是具体产品A类。
* ProductB1、ProductB2是具体产品B类。
* AbstractFactory:抽象工厂类
* ConcreteFactory1和ConcreteFactory2是抽象工厂类的实现,分别实现生产产品A1、B1和A2、B2。
* Client:生产产品。
* @author hexiaoli
*
*/
public class Client {
public static void main(String[] args) {
AbstractFactory abstractFactory1 = new ConcreteFacroty1();
AbstractProductA aProductA1 = abstractFactory1.creatProductA();
aProductA1.introduce();
AbstractProductB aProductB1 = abstractFactory1.creatProductB();
aProductB1.introduce();
AbstractFactory abstractFactory2 = new ConcreteFacroty2();
AbstractProductA aProductA2 = abstractFactory2.creatProductA();
aProductA2.introduce();
AbstractProductB aProductB2 = abstractFactory2.creatProductB();
aProductB2.introduce();
}
}