创建型设计模式-原型模式

原型模式是一种创建型设计模式,它允许通过复制现有对象来创建新对象,甚至是复杂对象,而又无需使代码依赖它们所属的类。
在这里插入图片描述

Shape:抽象原型类,声明具备clone能力,抽象原型类的作用是规范化克隆方法的使用,确保每个具体的原型类都有克隆方法,并且在运行时可以通过该方法来动态地创建新对象,例如java中的Cloneable接口
Rectangle/Circle:具体原型类,他实现抽象类中声明的克隆方法,在克隆方法中返回自己的克隆对象

代码示例
抽象原型类:Shape

@Data
public abstract class Shape implements Cloneable {
    private String type;

    @Override
    public Shape clone() {
        Shape clone = null;
        try {
            clone = (Shape) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

具体原型类:Rectangle

@Data
public class Rectangle extends Shape {
    private int length;

    private int width;

    public Rectangle(int length,int width) {
        this.length = length;
        this.width = width;
        setType("Rectangle");
    }
}

具体原型类:Circle

@Data
public class Circle extends Shape {
    private int radius;

    public Circle(int radius) {
        this.radius = radius;
        setType("Circle");
    }

}

运行示例:

    public static void main(String[] args) {
        Shape rectangle = new Rectangle(10,5);
        Shape rectangleClone = rectangle.clone();
        System.out.println(rectangle);
        System.out.println(rectangleClone);


        Shape circle = new Circle(10);
        Shape circleClone = circle.clone();
        System.out.println(circle);
        System.out.println(circleClone);
    }

在这个示例中,Shape 是原型接口,它实现了Cloneable接口,此处clone方法可以改成任意的名称,因为Cloneable接口是个空接口,你可以任意定义实现类的方法名,如cloneA或者cloneB,因为此处的重点是super.clone()这句话,super.clone()调用的是Object的clone()方法。
Rectangle 和 Circle 是具体的原型类。

优点

  • 减少对象的创建时间:避免了重复的初始化操作,直接通过复制现有对象进行创建,提高了对象创建的效率。
  • 简化对象创建过程:不需要关注对象的具体创建过程,只需克隆一个现有对象即可。

缺点

  • 深克隆问题:如果对象中含有引用类型的成员变量,需要实现深克隆才能保证克隆对象和原对象的引用类型不相互影响。

适用场景
当需要创建一个对象,但创建过程复杂或者依赖于现有对象时,可以考虑使用原型模式。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值