原型模式(Prototype Pattern)

原型模式(Prototype Pattern)是一种创建型设计模式,它允许你复制已有对象而无需使代码依赖它们所属的类。通常用于当创建对象的代价较高时,使用原型模式可以快速生成新对象。

以下是一个使用 Java 实现原型模式的示例:

示例:图形克隆

假设你正在开发一个图形编辑器,它允许用户绘制不同形状的图形(如圆形、矩形),并且你希望用户能够复制这些图形。

代码实现

  1. 创建 Shape 抽象类:定义基本的图形属性和克隆方法。
public abstract class Shape implements Cloneable {
    private String id;
    protected String type;

    abstract void draw();

    public String getType() {
        return type;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}
  1. 创建具体的图形类:如圆形和矩形。
public class Rectangle extends Shape {
    public Rectangle() {
        type = "Rectangle";
    }

    @Override
    public void draw() {
        System.out.println("Drawing a Rectangle");
    }
}

public class Circle extends Shape {
    public Circle() {
        type = "Circle";
    }

    @Override
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}
  1. 创建 ShapeCache:用于存储和管理图形的原型对象。
import java.util.Hashtable;

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

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

    // 模拟数据库的查询过程
    public static void loadCache() {
        Circle circle = new Circle();
        circle.setId("1");
        shapeMap.put(circle.getId(), circle);

        Rectangle rectangle = new Rectangle();
        rectangle.setId("2");
        shapeMap.put(rectangle.getId(), rectangle);
    }
}
  1. 客户端代码:从缓存中获取并克隆图形对象。
public class PrototypePatternDemo {
    public static void main(String[] args) {
        // 加载缓存中的图形
        ShapeCache.loadCache();

        // 获取克隆的对象
        Shape clonedShape1 = ShapeCache.getShape("1");
        System.out.println("Shape : " + clonedShape1.getType());
        clonedShape1.draw();

        Shape clonedShape2 = ShapeCache.getShape("2");
        System.out.println("Shape : " + clonedShape2.getType());
        clonedShape2.draw();
    }
}

输出结果

Shape : Circle
Drawing a Circle
Shape : Rectangle
Drawing a Rectangle

解释

在这个示例中,Shape 是一个抽象类,它实现了 Cloneable 接口,允许它的子类被克隆。RectangleCircleShape 的具体实现类。ShapeCache 类负责存储这些图形对象,并在需要时返回它们的克隆。

客户端通过调用 ShapeCache.getShape() 来获取图形的克隆,而不需要关心图形的具体实现或创建过程,这使得对象的复制过程更加简单和高效。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值