05设计模式之原型模式


一、什么是原型模式

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
《设计模式:可复用面向对象软件的基础》

原型模式个人理解,其实就是用标准的方法克隆当前对象。

二、原型模式如何实施

下面是一个原型模式的实现用例,其实也可以基于json、基于setter等等都可以,这些只是实施的具体方法,思想是相同即可。

1. 实现类

import org.apache.commons.lang3.SerializationUtils;

import java.io.Serializable;
import java.util.List;

public class BeanPrototype implements Cloneable, Serializable {

    private Integer id;

    private String name;
    
    private List<String> attributes;

    public BeanPrototype(Integer id, String name, List<String> attributes) {
        this.id = id;
        this.name = name;
        this.attributes = attributes;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<String> getAttributes() {
        return attributes;
    }

    @Override
    public BeanPrototype clone() {
        return SerializationUtils.clone(this);
    }
}

2. 使用

		BeanPrototype bean = new BeanPrototype(1,"名称", new LinkedList<>());
        BeanPrototype clone = bean.clone();//深拷贝

三、使用场景

  1. Spring的org.springframework.beans.factory.support.AbstractBeanDefinition#clone就是一个基于setter进行的深拷贝

参考资料

  1. 设计模式基于C#的实现与扩展——创建型模式(六)
  2. 23 种设计模式详解(全23种))
  3. 秒懂设计模式(五)-原型模式,你真的了解原型模式吗)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值