深入理解23种设计模式(3) -- 原型模式

介绍

  1. 原型模式(Prototype模式)指:用原型实例指定创建的种类,并且通过拷贝这些原型,创建新的对象
  2. 原型模式是哟中创建型设计模式,允许一个对象超级爱你再超级爱你另一个可定制的对象,无需知道创建的细节
  3. 工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建爱你,即 对象.clone()
    在这里插入图片描述
  • Prototype : 为原型类,声明一个克隆自身的接口
  • ConcretePrototype : 为具体实现类,实现一个克隆自身的操作;而客户端Client只需让一个原型克隆自身,从而创建一个新的对象。

案例

  1. 现在有一只羊tom ,姓名为 :tom,颜色为:白色,请编写程序创建和tom羊完全属性相同的10只羊

之前的写法 :

新建Sheep 类

@Data
public class Sheep {
    //姓名
    private String name;
    //年龄
    private Integer age;
    //颜色
    private String color;

	public Sheep(String name, Integer age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }
}

编写测试类

public class Test {
    public static void main(String[] args) {
		Sheep sheep =new Sheep("tom",1,"白色");
        Sheep sheep2 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        Sheep sheep3 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        Sheep sheep4 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        System.out.println(sheep);
        System.out.println(sheep2);
        System.out.println(sheep3);
        System.out.println(sheep4);
    }
}

在这里插入图片描述

  • 传统方式解决克隆羊的问题
  1. 有点好理解,简单
  2. 在创建新的对象的时候,总是需要重新获取原始对象的属性,如果创建对象复杂,效率低,不够灵活

使用原型模式 代码改造

@Data
public class Sheep implements Cloneable{
    //姓名
    private String name;
    //年龄
    private Integer age;
    //颜色
    private String color;

    public Sheep(String name, Integer age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    //克隆该实例,默认实用化clone方法来完成
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Sheep sheep = null;
        sheep =(Sheep)super.clone();
        return sheep;
    }

 public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheep =new Sheep("tom",1,"白色");
        Sheep sheep2= (Sheep) sheep.clone();
        System.out.println(sheep);
        System.out.println(sheep2);

    }

在这里插入图片描述

优点和缺点

优点:

1)性能优良。不用重新初始化对象,而是动态地获取对象运行时的状态。
2)逃避构造函数的约束。

缺点:

 1)配置克隆方法需要对类的功能进行通盘考虑。
 2)必须实现Cloneable接口。

适用场景:

 1) 一般与工厂方法模式一起出现,通过clone方法创建一个对象,然后由工厂方法提供给调用者。


  • 原型模式在Spring框架中应用
//已原型模式创建
<bean id ="id" class="com.yxl.bean.Monster" scope="prototype">

github Demo地址 : ~~~传送门~~~

个人博客地址:http://blog.yanxiaolong.cn/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值