欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

23种设计模式之原型模式prototype

程序员文章站 2022-06-13 08:02:06
...

* 当使用New关键字实例化对象的时候,很复杂,可以考虑原型模式来实现!强调内容 再则就是New对象比较耗时,克隆(clone)比较节省时间!*

浅克隆

public class Sheep implements Cloneable {
    private String name;
    private Date birthday;

    public Sheep(String name, Date birthday) {
        this.name = name;
        this.birthday = birthday;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object object = super.clone();

        return object;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

测试

  Date date = new Date();
        Sheep sheep = new Sheep("喜洋洋", date);
        System.out.println(sheep.toString());

        //修改date值
        date.setTime(1000000);
        System.out.println(sheep.getBirthday());

        Sheep s2 = (Sheep) sheep.clone();//复制一只懒洋洋
        s2.setName("懒洋洋");
        System.out.println(s2.toString());

深克隆

public class Sheep1 implements Cloneable {
    private String name;
    private Date birthday;

    public Sheep1(String name, Date birthday) {
        this.name = name;
        this.birthday = birthday;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object object = super.clone();
        Sheep1 sheep= (Sheep1) object;
        sheep.birthday= (Date) this.birthday.clone();//属性进行复制
        return object;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

测试

 Date date = new Date();
        Sheep1 sheep = new Sheep1("喜洋洋", date);
        Sheep1 s2 = (Sheep1) sheep.clone();//复制一只懒洋洋
        System.out.println(sheep.toString());

        //修改date值
        date.setTime(1000000);
        System.out.println(sheep.getBirthday());


        s2.setName("懒洋洋");
        System.out.println(s2.toString());

总结:原型模式其实就是复制,就好比,上学的时候,写试卷,你花一个小时写完,同座拿过去抄复制,只花了三分钟,并且他还自己可以修改错误。浅克隆和深克隆的区别:浅克隆相当于复制了一个自己,名字随你改,但是一些共同属性,比如毁容了啊,两个就一起毁了;深克隆就是我复制了你所有东西,然后我翻身自己当主人了。你毁容和我没关系

相关标签: 原型模式