- 抽象工厂类或接口
public interface AbstractFactory {
public AbstractProductA createProductA();
public AbstractProductB createProductB();
}
- 抽象工厂类或接口实现类
public class ConcreteFactory1 implements AbstractFactory {
@Override
public AbstractProductA createProductA() {
return new ConcreteProductA1();
}
@Override
public AbstractProductB createProductB() {
return new ConcreteProductB1();
}
}
public class ConcreteFactory2 implements AbstractFactory {
@Override
public AbstractProductA createProductA() {
return new ConcreteProductA2();
}
@Override
public AbstractProductB createProductB() {
return new ConcreteProductB2();
}
}
- 抽象产品类或接口
public abstract class AbstractProductA {
public abstract void doSomething();
}
public abstract class AbstractProductB {
public abstract void doAnything();
}
- 抽象产品类或接口实现类
public class ConcreteProductA1 extends AbstractProductA{
@Override
public void doSomething() {
//具体处理
}
}
public class ConcreteProductA2 extends AbstractProductA{
@Override
public void doSomething() {
//具体处理
}
}
public class ConcreteProductB1 extends AbstractProductB {
@Override
public void doAnything() {
//具体处理
}
}
public class ConcreteProductB2 extends AbstractProductB {
@Override
public void doAnything() {
//具体处理
}
}
- 使用
AbstractFactory factory1 = new ConcreteFactory1();
AbstractProductA productA1 = factory1.createProductA();
AbstractProductB productB1 = factory1.createProductB();
AbstractFactory factory2 = new ConcreteFactory2();
AbstractProductA productA2 = factory2.createProductA();
AbstractProductB productB2 = factory2.createProductB();
网友评论