通过策略模式实现对象创建工厂
目录
案例:通过策略模式实现对象创建工厂
场景描述:
设计步骤:
注:
案例:通过策略模式实现对象创建工厂
场景描述:
假设要设计一个系统,用来创建不同类型的 Shape
对象(如 Circle
、Square
、Rectangle
)。通常会使用工厂模式来封装对象创建的过程。但是,我们尝试用策略模式来实现这个功能,使得对象的创建方式在运行时动态调整。
设计步骤:
- 定义Shape接口及其实现类:
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Rectangle");
}
}
- 定义创建策略接口及其实现类:
interface ShapeCreationStrategy {
Shape createShape();
}
class CircleCreationStrategy implements ShapeCreationStrategy {
@Override
public Shape createShape() {
return new Circle();
}
}
class SquareCreationStrategy implements ShapeCreationStrategy {
@Override
public Shape createShape() {
return new Square();
}
}
class RectangleCreationStrategy implements ShapeCreationStrategy {
@Override
public Shape createShape() {
return new Rectangle();
}
}
- 定义一个上下文类,用来选择和使用不同的策略:
class ShapeFactoryContext { private ShapeCreationStrategy strategy; public void setStrategy(ShapeCreationStrategy strategy) { this.strategy = strategy; } public Shape createShape() { return strategy.createShape(); } }
- 客户端代码:
public class Main { public static void main(String[] args) { ShapeFactoryContext context = new ShapeFactoryContext(); // 使用CircleCreationStrategy context.setStrategy(new CircleCreationStrategy()); Shape shape1 = context.createShape(); shape1.draw(); // 输出: Drawing a Circle // 使用SquareCreationStrategy context.setStrategy(new SquareCreationStrategy()); Shape shape2 = context.createShape(); shape2.draw(); // 输出: Drawing a Square // 使用RectangleCreationStrategy context.setStrategy(new RectangleCreationStrategy()); Shape shape3 = context.createShape(); shape3.draw(); // 输出: Drawing a Rectangle } }
注:
以上通过策略模式实现了一个动态可变的“工厂”。没有使用传统的工厂模式,而是利用策略模式的思想,动态选择创建对象的策略。