世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
- 意图
通过克隆拷贝一个与原对象内容相同但是地址不同的另一个对象,两者后续操作不会相互影响,克隆对象相当于原对象某一时间点的快照。 - 类图
- 实例
class Shape implements Cloneable {
private String name;
public Shape getClone () {
try {
return (Shape)this.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 测试
public class PrototypeDemo {
public static void main(String[] args) {
Shape shape = new Shape();
shape.setName("shape");
Shape shape1 = shape.getClone();
System.out.println(shape1.getName());
shape1.setName("shape1");
System.out.println(shape.getName() + " --- " + shape1.getName());
}
}
运行结果:
shape
shape --- shape1