抽象工厂模式详解
理解
抽象工厂模式是围绕一个超级工厂创建其他工厂,该超级工厂又称为其他工厂的工厂,这些由超级工厂创建的工厂可以创造一系列的产品。在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类,每个生成的工厂都能按照工厂模式提供对象。
示例
工作了,为了参加一些聚会,肯定有两套或多套衣服吧,比如说有商务装(成套,一系列具体产品)、时尚装(成套,一系列具体产品)。
定义衣服,裤子,创建服装的工厂的抽象接口
public interface Clothing {
void wear();
}
public interface Pants {
void wear();
}
public interface ClothesFactory {
Clothing getClothing();
Pants getPants();
}
假设有一个商务工厂负责生产衣服和裤子,下面是商务工厂对以上接口的实现,这里使用了Lambda表达式实现接口。
public class BusinessClothesFactory implements ClothesFactory {
@Override
public Clothing getClothing() {
return () -> System.out.println("wearing business clothing");
}
@Override
public Pants getPants() {
return () -> System.out.println("wearing business pants");
}
}
假设有一个时尚工厂负责生产衣服和裤子,下面是时尚工厂对以上接口的实现,这里使用了Lambda表达式实现接口。
public class FashionClothesFactory implements ClothesFactory {
@Override
public Clothing getClothing() {
return () -> System.out.println("wearing fashion clothing");
}
@Override
public Pants getPants() {
return () -> System.out.println("wearing fashion pants");
}
}
测试主启动类
public static void main(String[] args) {
//穿一套商务装
ClothesFactory businessClothesFactory = new BusinessClothesFactory();
Clothing businessClothing = businessClothesFactory.getClothing();
Pants businessPants = businessClothesFactory.getPants();
businessClothing.wear();//out --> wearing business clothing
businessPants.wear();//out --> wearing business pants
//穿一套时尚装
ClothesFactory fashionClothesFactory = new FashionClothesFactory();
Clothing fashionClothing = fashionClothesFactory.getClothing();
Pants fashionPants = fashionClothesFactory.getPants();
fashionClothing.wear();//out --> wearing fashion clothing
fashionPants.wear();//out --> wearing fashion pants
}
使用场景
- 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
- 工厂创建的一系列产品类别已经定型(这是因为添加新的产品类别是十分复杂的)
- 工厂创建的一系列产品需要扩展新的工厂(添加新的工厂是容易的)
运用
- java.sql.Connection就是一个经典的抽象工厂。这个大佬有详细的解读,非常的牛: 抽象工厂模式及其在Java源码中的应用
总结
优点:
- 扩展性高,如果想增加一个工厂,或是一系列产品,只要扩展一个工厂类及相关创建的产品就可以,不会改动原本的类(比如上述实例中如果增加一个休闲套装只需要创建休闲服装工厂,实现服装接口就可以)。
缺点:
- 工厂创建的一系列产品类别已经定型,添加新的产品类别是十分复杂的,需要改动超级工厂抽象类以及所有工厂的方法(比如上述实例中如果增加一个帽子作为所有工厂的一个生产的铲平,则需要改动超级工厂抽象类以及所有服装工厂的方法)。