欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > 通过策略模式实现对象创建工厂

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

2024/10/25 4:23:08 来源:https://blog.csdn.net/weixin_43298211/article/details/142235830  浏览:    关键词:通过策略模式实现对象创建工厂

目录

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

场景描述:

设计步骤:

注:


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

场景描述:

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

设计步骤:
  • 定义Shape接口及其实现类:
interface Shape {void draw();
}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");}
}class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a Rectangle");}
}
  • 定义创建策略接口及其实现类:
interface ShapeCreationStrategy {Shape createShape();
}class CircleCreationStrategy implements ShapeCreationStrategy {@Overridepublic Shape createShape() {return new Circle();}
}class SquareCreationStrategy implements ShapeCreationStrategy {@Overridepublic Shape createShape() {return new Square();}
}class RectangleCreationStrategy implements ShapeCreationStrategy {@Overridepublic 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();// 使用CircleCreationStrategycontext.setStrategy(new CircleCreationStrategy());Shape shape1 = context.createShape();shape1.draw(); // 输出: Drawing a Circle// 使用SquareCreationStrategycontext.setStrategy(new SquareCreationStrategy());Shape shape2 = context.createShape();shape2.draw(); // 输出: Drawing a Square// 使用RectangleCreationStrategycontext.setStrategy(new RectangleCreationStrategy());Shape shape3 = context.createShape();shape3.draw(); // 输出: Drawing a Rectangle}
    }

    注:

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

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com