常用设计模式5:原型模式(Java)

原型模式(Prototype Pattern)

1. 简介

原型模式是一种创建型设计模式,它允许复制已有对象,而无需使代码依赖它们所属的类。该模式声明了一个共同的接口,使用该接口能够复制对象,即使该对象的具体类型未知。

2. 为什么使用原型模式?

  • 性能优化:在某些情况下,创建新对象的成本可能很高,复制现有对象可能更高效。
  • 简化对象创建:避免复杂的初始化过程。
  • 动态运行时配置:可以在运行时动态添加或删除原型。
  • 减少子类数量:可以替代工厂方法模式中的继承。

3. 原型模式的结构

原型模式主要包含以下角色:

  1. Prototype:原型接口,声明克隆方法。
  2. ConcretePrototype:具体原型类,实现克隆方法。
  3. Client:客户类,使用原型接口创建新的对象。

4. Java 实现示例

下面是一个简单的形状克隆的例子来说明原型模式:

4.1 定义原型接口

public interface Shape extends Cloneable {
    Shape clone();
    void draw();
}

4.2 实现具体原型

public class Circle implements Shape {
    private int x, y, radius;

    public Circle(int x, int y, int radius) {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    @Override
    public Shape clone() {
        return new Circle(this.x, this.y, this.radius);
    }

    @Override
    public void draw() {
        System.out.println("Drawing Circle at (" + x + "," + y + ") with radius " + radius);
    }
}

public class Rectangle implements Shape {
    private int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public Shape clone() {
        return new Rectangle(this.width, this.height);
    }

    @Override
    public void draw() {
        System.out.println("Drawing Rectangle with width " + width + " and height " + height);
    }
}

4.3 实现原型管理器(可选)

public class ShapeCache {
    private static Map<String, Shape> shapeMap = new HashMap<>();

    public static void loadCache() {
        Circle circle = new Circle(10, 10, 5);
        shapeMap.put("Circle", circle);

        Rectangle rectangle = new Rectangle(10, 20);
        shapeMap.put("Rectangle", rectangle);
    }

    public static Shape getShape(String shapeId) {
        Shape cachedShape = shapeMap.get(shapeId);
        return cachedShape.clone();
    }
}

4.4 客户端代码

public class Client {
    public static void main(String[] args) {
        ShapeCache.loadCache();

        Shape clonedShape1 = ShapeCache.getShape("Circle");
        System.out.println("Shape : " + clonedShape1.getClass().getSimpleName());
        clonedShape1.draw();

        Shape clonedShape2 = ShapeCache.getShape("Rectangle");
        System.out.println("Shape : " + clonedShape2.getClass().getSimpleName());
        clonedShape2.draw();
    }
}

5. 原型模式的优缺点

优点:

  • 可以在运行时添加和删除原型。
  • 减少子类的构建。
  • 可以动态配置应用程序。
  • 避免重复的初始化代码。

缺点:

  • 克隆包含循环引用的复杂对象可能会非常麻烦。
  • 实现克隆方法可能会很困难,特别是当对象有多个私有字段时。

6. 适用场景

  • 当一个系统应该独立于它的产品创建、构成和表示时。
  • 当要实例化的类是在运行时刻指定时。
  • 为了避免创建一个与产品类层次平行的工厂类层次时。
  • 当一个类的实例只能有几个不同状态组合中的一种时。

7. 总结

原型模式提供了一种创建对象的方法,它不依赖于对象的具体类型。通过复制现有的对象来创建新对象,原型模式可某些情况下提高性能,并简化对象的创建过程。特别适用于那些创建对象的成本较高,或者需要动态配置对象的场景。然而,在实现时需要注意处理深拷贝和浅拷贝的问题,特别是在处理复杂对象时。

posted @ 2024-08-04 21:24  KenWan  阅读(98)  评论(0)    收藏  举报