接着昨天的工厂模式接着说说抽象工厂,当你拥有多个抽象对象的时候。你的工厂模式估计就不给力了。这时候你就该考虑抽象工厂了。抽象工厂模式可以向客户端提供一个接口,使客户端在不必指定产品的具体的情况下,创建多个产品族中的产品对象
不说了上代码。
package AbstractFactory;
public interface AbstractFactory {
public AbstractProduct createConcreteProductA();
public AbstractProduct createConcreteProductB();
}
package AbstractFactory;
public interface AbstractProduct {
public void doSomething();
}
package AbstractFactory;
public class ConcreteFactory implements AbstractFactory {
public ConcreteFactory() {
super();
}
public AbstractProduct createConcreteProductA() {
return new ConcreteProductA();
}
public AbstractProduct createConcreteProductB() {
return new ConcreteProductB();
}
}
package AbstractFactory;
public class ConcreteProductA implements AbstractProduct {
public ConcreteProductA() {
super();
}
public void doSomething() {
System.out.println("A产品");
}
}
package AbstractFactory;
public class ConcreteProductB implements AbstractProduct {
public ConcreteProductB() {
super();
}
public void doSomething() {
System.out.println("B产品");
}
}
package AbstractFactory;
public class ClientA {
private final AbstractFactory fFactory;
public ClientA(AbstractFactory factory) {
super();
fFactory = factory;
}
public void useConcreteProductA() {
final AbstractProduct product = fFactory.createConcreteProductA();
product.doSomething();
}
public void useConcreteProductB() {
final AbstractProduct product = fFactory.createConcreteProductB();
product.doSomething();
}
}
package AbstractFactory;
public class ClientB {
private final AbstractFactory fFactory;
public ClientB(AbstractFactory factory) {
super();
fFactory = factory;
}
public void useConcreteProductA() {
final AbstractProduct product = fFactory.createConcreteProductA();
product.doSomething();
}
public void useConcreteProductB() {
final AbstractProduct product = fFactory.createConcreteProductB();
product.doSomething();
}
}
package AbstractFactory;
public class AbstractFactoryTest {
public static void main(String[] args) {
ClientA clientA = new ClientA(new ConcreteFactory());
clientA.useConcreteProductA();
clientA.useConcreteProductB();
ClientB clientB = new ClientB(new ConcreteFactory());
clientB.useConcreteProductA();
clientB.useConcreteProductB();
}
}
这里的代码并没有用抽象的类,而是使用的接口。