原型模型

通过new产生一个对象需要非常繁琐的数据准备或访问权限,则可以使用原型模式。

-就是java中的克隆技术,以某个对象为原型,复制出新的对象。显然,新的对象具备原型对象的特点 -优势有:效率高(直接克隆,避免了重新执行构造过程步骤)。

-克隆类似于new ,但是不同于new。new创建新的对象属性采用的是默认值。克隆出的 对象的属性值完全和原型对象相同。并且克隆出的新对象改变不会影响原型对象。然后, 再修改克隆对象的值。

 

实现

- Cloneable接口和clone方法

/**
 * 原型模式
 */
public class Sheep implements Cloneable{
    private String sname;
    private Date birthday;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Sheep() {
    }

    public Sheep(String sname, Date birthday) {
        this.sname = sname;
        this.birthday = birthday;
    }
}
//---------------------------

public class PrototypePatternTest {

    public  static void prototypePatternTest01() {
        System.out.println("----------------------------原型模式演示开始------------------------------------");
        System.out.println("--------------------创建一个原型------------------------");
        Sheep sheep1 = new Sheep("原型",new Date());
        System.out.println(sheep1);

        System.out.println(sheep1.getBirthday());
        System.out.println( sheep1.getSname());

        System.out.println("--------------------拷贝这个原型------------------------");
        Sheep sheep2 = null;
        try {
            sheep2 = (Sheep) sheep1.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        System.out.println("--------------------打印------------------------");
        System.out.println(sheep2);
        System.out.println(sheep2.getBirthday());
        System.out.println( sheep2.getSname());
        System.out.println("----------------------------原型模式演示结束------------------------------------");
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值