抽象工厂模式
是一个创建型设计模式,主要用于创建一系列相关或相互依赖的对象,而无需指定它们具体的类。它提供一个接口,用于创建相关或依赖对象的家族,而无需明确指定具体类。
优点
- 隔离具体类:客户端使用抽象工厂来创建对象,而不是直接使用具体类。这使得客户端与具体类解耦,从而更容易扩展和维护。
- 产品一致性:确保同一个工厂创建的一系列对象是相互匹配和一致的。
- 易于交换产品系列:更换产品系列只需要更换工厂实例,而不需要修改客户端代码。
缺点
- 难以支持新种类的产品:如果需要在产品系列中添加新产品,需要修改抽象工厂接口及其所有具体实现,这违反了开闭原则。
代码实现
假设我们有两种风格的家具系列:现代风格和维多利亚风格,每个系列有椅子和沙发。
1. 抽象产品
首先定义椅子和沙发的抽象产品接口。
// Chair interface
public interface Chair {
void sitOn();
}
// Sofa interface
public interface Sofa {
void lieOn();
}
2. 具体产品
实现现代风格和维多利亚风格的椅子和沙发。
// Modern Chair
public class ModernChair implements Chair {
@Override
public void sitOn() {
System.out.println("Sitting on a modern chair.");
}
}
// Victorian Chair
public class VictorianChair implements Chair {
@Override
public void sitOn() {
System.out.println("Sitting on a Victorian chair.");
}
}
// Modern Sofa
public class ModernSofa implements Sofa {
@Override
public void lieOn() {
System.out.println("Lying on a modern sofa.");
}
}
// Victorian Sofa
public class VictorianSofa implements Sofa {
@Override
public void lieOn() {
System.out.println("Lying on a Victorian sofa.");
}
}
3. 抽象工厂
定义抽象工厂接口,用于创建椅子和沙发。
// Furniture Factory interface
public interface FurnitureFactory {
Chair createChair();
Sofa createSofa();
}
4. 具体工厂
实现现代风格和维多利亚风格家具的具体工厂。
// Modern Furniture Factory
public class ModernFurnitureFactory implements FurnitureFactory {
@Override
public Chair createChair() {
return new ModernChair();
}
@Override
public Sofa createSofa() {
return new ModernSofa();
}
}
// Victorian Furniture Factory
public class VictorianFurnitureFactory implements FurnitureFactory {
@Override
public Chair createChair() {
return new VictorianChair();
}
@Override
public Sofa createSofa() {
return new VictorianSofa();
}
}
5. 客户端
客户端代码通过使用抽象工厂接口来创建具体产品。
public class Client {
private Chair chair;
private Sofa sofa;
public Client(FurnitureFactory factory) {
chair = factory.createChair();
sofa = factory.createSofa();
}
public void run() {
chair.sitOn();
sofa.lieOn();
}
public static void main(String[] args) {
System.out.println("Client: Testing client code with the Modern Furniture Factory:");
Client client1 = new Client(new ModernFurnitureFactory());
client1.run();
System.out.println("\nClient: Testing the same client code with the Victorian Furniture Factory:");
Client client2 = new Client(new VictorianFurnitureFactory());
client2.run();
}
}
运行结果
运行上述代码将输出:
Client: Testing client code with the Modern Furniture Factory:
Sitting on a modern chair.
Lying on a modern sofa.
Client: Testing the same client code with the Victorian Furniture Factory:
Sitting on a Victorian chair.
Lying on a Victorian sofa.