设计模式研究

原型模式

2020-08-03  本文已影响0人  Stephenwish
原型模式和迭代器模式,使用场景比较特殊,原型模式就是用来clone 对象的,假设对象很多属性要赋值,new 一个对象就需要一个个填写属性,当然你也可以ctrl +c
public class Thing implements Cloneable {
    private String name=null;

    public Thing(String name) {
        this.name = name;
    }

    @Override
    protected Thing clone() throws CloneNotSupportedException {

        return (Thing) super.clone();
    }

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

    public String getName() {
        return name;
    }

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

public class Client {
    public static void main(String[] args) {
        Thing hello = new Thing("hello");
        try {
            Thing clone = hello.clone();
            System.err.println(clone);
            clone.setName("wo");
            System.err.println(hello);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

有个主意地方,克隆时候如果是基本类型和String对象,他是直接拷贝,遇到引用类型他是浅拷贝,拷贝的只是引用,改了副本改了值还是会关联到原本

public class Thing implements Cloneable {
    private String name=null;
    private ArrayList<String> stringList=new ArrayList<>();

    public Thing(String name) {
        this.name = name;
    }

    @Override
    public Thing clone() throws CloneNotSupportedException {

        Thing clone1 = (Thing) super.clone();
        clone1.stringList = (ArrayList<String>) this.stringList.clone();
        return clone1;

    }


    public void addString(String string){
        stringList.add(string);
    }


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

    public String getName() {
        return name;
    }

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

public class Client {
    public static void main(String[] args) {
        Thing hello = new Thing("hello");
        hello.addString("AAA");
        try {
            Thing clone = hello.clone();
            System.err.println(clone);
            clone.setName("wo");
            clone.addString("BBBB");
            System.err.println(hello);
            //-------------------------------

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
上面例子测试了浅拷贝和深拷贝,ArrayList 要引用,不能用List,List没实现clone 接口
上一篇下一篇

猜你喜欢

热点阅读