通过策略模式实现对象创建工厂

目录

案例:通过策略模式实现对象创建工厂

场景描述:

设计步骤:

注:


案例:通过策略模式实现对象创建工厂

场景描述:

假设要设计一个系统,用来创建不同类型的 Shape 对象(如 CircleSquareRectangle)。通常会使用工厂模式来封装对象创建的过程。但是,我们尝试用策略模式来实现这个功能,使得对象的创建方式在运行时动态调整。

设计步骤:
  • 定义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
        }
    }

    注:

       以上通过策略模式实现了一个动态可变的“工厂”。没有使用传统的工厂模式,而是利用策略模式的思想,动态选择创建对象的策略。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何遇mirror

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值