1.抽象工厂结构图
示例代码:
// 抽象工厂类
public abstract class AbstractFactory {
protected abstract FoodProduct createProductA();
protected abstract BookProduct createProductB();
}
// 具体工厂类A
public class FamilyAFactory extends AbstractFactory{
@Override
protected FoodProduct createProductA() {
return new FamilyAProductA();
}
@Override
protected BookProduct createProductB() {
return new FamilyAProductB();
}
}
// 具体工厂类B
public class FamilyBFactory extends AbstractFactory{
@Override
protected FoodProduct createProductA() {
return new FamilyBProductA();
}
@Override
protected BookProduct createProductB() {
return new FamilyBProductB();
}
}
// 抽象产品书籍
public abstract class BookProduct {
public abstract void read();
}
// familyA生产的书籍
public class FamilyABook extends BookProduct {
@Override
public void read() {
System.out.println("这是FamilyA生产的书籍!");
}
}
// familyB生产的书籍
public class FamilyBBook extends BookProduct {
@Override
public void read() {
System.out.println("这是FamilyB生产的书籍!");
}
}
// 抽象产品食物
public abstract class FoodProduct {
public abstract void eat() ;
}
// familyA生产的食物
public class FamilyAFood extends FoodProduct {
@Override
public void eat() {
System.out.println("这是FamilyA生产的食物!");
}
}
// familyB生产的食物
public class FamilyBFood extends FoodProduct {
@Override
public void eat() {
System.out.println("这是FamilyB生产的食物!");
}
}
// 测试
public class AbstractFactoryTest {
public static void main(String[] args) {
AbstractFactory aFactory = new FamilyAFactory();
FoodProduct familyAproductA = aFactory.createProductA();
familyAproductA.eat();
BookProduct familyAProductB = aFactory.createProductB();
familyAProductB.read();
}
}
总结:
优点:增加了程序的可扩展性,需要增加新的产品族时,只需要实现一个新的工厂即可,符合开闭原则;
缺点:产品族扩展新的产品困难,需要修改抽象工厂的接口,增加了系统的抽象性和理解难度.
原文:https://www.cnblogs.com/wqlken/p/14645253.html