用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象;
也叫克隆模式;
2.角色- Prototype:抽象原型类 声明clone() 的接口或者基类,其中clone()方法必须是子类实现(Java。。)
- ConcretePrototype:实现clone() 方法,返回拷贝后的实例
java 对象实现 Cloneable() 接口,并且重写 clone() 方法,得到原来对象的拷贝对象;但是有问题需要注意;
浅拷贝和深拷贝
java中的原始的拷贝方法(super.clone()) 是一个浅拷贝 ,次方法用来拷贝对象
protected native Object clone() throws CloneNotSupportedException;
注:是一个本地方法;一个对象被拷贝,是一个对象的内存复制一份,指向另一个引用;其中基础类型是值拷贝,而引用类型拷贝是引用,而不是拷贝具体对象中的数据
深拷贝的话,还是需要自己去实现clone() 方法;
在具体的代码工程实践中,还是根据具体的实战需求来实现对对象的深拷贝,浅拷贝,或者是混合拷贝;
4.写个例子 4.1 浅拷贝class People implements Cloneable {
public Integer age;
public String name;
public Address address;
@Override
protected People clone() throws CloneNotSupportedException {
return (People) super.clone();
}
@Override
public String toString() {
return "People{" + "age=" + age + ", name='" + name + ''' + ", address=" + address + '}';
}
}
class Address implements Cloneable {
public String province;
public String city;
public String street;
@Override
protected Address clone() throws CloneNotSupportedException {
return (Address) super.clone();
}
@Override
public String toString() {
return "Address{" + "province='" + province + ''' + ", city='" + city + ''' + ", street='" + street + '''
+ '}';
}
}
Main
public static void main(String[] args) throws CloneNotSupportedException {
People student = new People();
student.name = "sff";
student.age = 20;
Address address = new Address();
address.province = "安徽芜湖";
address.city = "芜湖";
address.street = "xx街道";
student.address = address;
People clone = student.clone();
System.out.println(clone);
address.city = "合肥";
System.out.println(student);
System.out.println(clone);
}
People{age=20, name='sff', address=Address{province='安徽芜湖', city='合肥', street='xx街道'}}
People{age=20, name='sff', address=Address{province='安徽芜湖', city='合肥', street='xx街道'}}
对People 的address 是浅拷贝,拷贝是引用,所以当address.city = “合肥”; 发生改变的时候 ,student 和 clone 都持有这个引用 所以都发生了改变;
4.2 浅拷贝// 修改 People 方法 clone() ,对有引用对象 拷贝一次,重写生成一个Address对象
@Override
protected People clone() throws CloneNotSupportedException {
People clone = (People) super.clone();
clone.address = address.clone();
return clone;
}
测试
People{age=20, name='sff', address=Address{province='安徽芜湖', city='合肥', street='xx街道'}}
People{age=20, name='sff', address=Address{province='安徽芜湖', city='芜湖', street='xx街道'}}
对原有对象 student 得 address 的修改不会映射到 clone 对象的 address 中



