在Abstract Factory模式中,存在抽象工厂和抽象产品
UML
示例代码
Product
1 2 3 4 5
| public abstract class AbstractProductA {
protected abstract void doSomething();
}
|
1 2 3 4 5 6
| public class ConcreteProductA1 extends AbstractProductA{ @Override protected void doSomething() { System.out.println("concrete product A1"); } }
|
1 2 3 4 5 6
| public class ConcreteProductA2 extends AbstractProductA{ @Override protected void doSomething() { System.out.println("concrete product A2"); } }
|
Factory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public abstract class AbstractFactory {
public static <T extends AbstractFactory> AbstractFactory getFactory(Class<T> clz) { AbstractFactory factory = null; try { factory = (AbstractFactory) Class.forName(clz.getName()).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return factory; }
public abstract AbstractProductA createProductA(); }
|
1 2 3 4 5 6 7
| public class ConcreteFactory1 extends AbstractFactory{ @Override public AbstractProductA createProductA() { return new ConcreteProductA1(); } }
|
1 2 3 4 5 6 7
| public class ConcreteFactory2 extends AbstractFactory{
@Override public AbstractProductA createProductA() { return new ConcreteProductA2(); } }
|
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Client { public static void main(String[] args) {
AbstractFactory factory; AbstractProductA product;
factory = AbstractFactory.getFactory(ConcreteFactory1.class); product = factory.createProductA(); product.doSomething();
factory = AbstractFactory.getFactory(ConcreteFactory2.class); product = factory.createProductA(); product.doSomething();
} }
|
只要知道工厂类,就能创建出一个需要的对象