抽象工厂模式(Abstract Factory)
抽象工厂模式是一种创建型设计模式,提供一个创建一系列相关或互相依赖对象的接口,而无需指定具体的类。
适用场景:
- 当系统需要独立于产品的创建、组合和表示时。
- 当系统的产品有多个变体并且需要组合使用时。
示例代码:
// AbstractProduct
interface Shape {void draw();
}// ConcreteProducts
class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a Circle");}
}class Square implements Shape {@Overridepublic void draw() {System.out.println("Drawing a Square");}
}// AbstractFactory
interface ShapeFactory {Shape createShape();
}// ConcreteFactories
class CircleFactory implements ShapeFactory {@Overridepublic Shape createShape() {return new Circle();}
}class SquareFactory implements ShapeFactory {@Overridepublic Shape createShape() {return new Square();}
}class Client {public static void main(String[] args) {ShapeFactory factory = new CircleFactory();Shape shape = factory.createShape();shape.draw(); // 输出: Drawing a Circle}
}