设计模式之原型模式的学习思考

来源:互联网 发布:安康市 软件正版 编辑:程序博客网 时间:2024/06/05 19:12

原型模式是设计模式里的创建型模式,通过对象来创建对象,一般通过克隆来实现。

克隆有浅克隆和深克隆之分:是对类内部对象引用的克隆程度

  1. 浅克隆后,新对象类的基本数值独立,但是克隆的对象引用只是地址,原对象改变,新克隆的对象也会改变;
  2. 深克隆,完全克隆,源对象的改变无论是基本数值还是对象引用都不会对新对象造成影响。

小例子:

  1. 浅拷贝:
import java.util.ArrayList;import java.util.List;class People implements Cloneable{    private String name;    private int age;    private List<String> re;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public List<String> getRe() {        return re;    }    public void setRe(List<String> re) {        this.re = re;    }    public People clone(){        try {            return (People)super.clone();        } catch (CloneNotSupportedException e) {            // TODO Auto-generated catch block            e.printStackTrace();            return null;        }    }}public class PrototypePattern {    public static void main(String[] args) {        People p1=new People();        p1.setName("ds");        p1.setAge(7);        List<String> ll=new ArrayList<String>();        ll.add("呵呵");        p1.setRe(ll);        People p2=p1.clone();        System.out.println(p1.getName());        System.out.println(p1.getRe());        System.out.println(p2.getName());        System.out.println(p2.getRe());        p1.setName("dsds");        ll.add("呵呵呵呵");        System.out.println(p2.getName());   //  p2基本数据没有改变        System.out.println(p2.getRe());     //  p2内部对象引用改变    }}

输出:

ds[呵呵]ds[呵呵]ds[呵呵, 呵呵呵呵]
  1. 深拷贝:
import java.util.ArrayList;import java.util.List;class People implements Cloneable{    private String name;    private int age;    private List<String> re;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public List<String> getRe() {        return re;    }    public void setRe(List<String> re) {        this.re = re;    }    public People clone(){        try {            People person=(People)super.clone();            List<String> newre=new ArrayList<String>();            for(String r:newre){                newre.add(r);            }            person.setRe(newre);            return person;        } catch (CloneNotSupportedException e) {            // TODO Auto-generated catch block            e.printStackTrace();            return null;        }    }}public class PrototypePattern {    public static void main(String[] args) {        People p1=new People();        List<String> ll=new ArrayList<String>();        ll.add("哦哦");        p1.setRe(ll);        People p2=p1.clone();        System.out.println(p1.getRe());        System.out.println(p2.getRe());    }}

输出:

[哦哦][]
原创粉丝点击