1.定义说明
- 定义说明
原型,顾名思义是一个模板
通过拷贝原型来创建新的对象
- 使用场景
类初始化消耗资源太多时,可以用原型模型
当new操作成本较高时,clone方法可以带来效率提升
2.UML类图
- 角色介绍:
Client:用户类
IProtoType:接口or抽象类,原型模板,具备clone能力
ConcreteProtoType:具体原型类
- 要点
clone方法是Object类的方法,Clonetable只是标识接口
clone对象时,构造方法不会执行!!!
3.UML示例代码
public class Hero implements Cloneable {
private static final String TAG = "Hero";
private String name;
private int age;
private String sect;
public Hero() {
Log.d(TAG, "Construct method");
}
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 String getSect() {
return sect;
}
public void setSect(String sect) {
this.sect = sect;
}
@Override
protected Hero clone() {
try {
Hero hero = (Hero) super.clone();
hero.name = this.name;
hero.age = this.age;
hero.sect = this.sect;
return hero;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
@Override
public String toString() {
return "Hero{" +
"name='" + name + '\'' +
", age=" + age +
", sect='" + sect + '\'' +
'}';
}
}
4.源码中应用
- Intent覆写了clone方法,直接返回新对象,因为构造Intent对象成本较小
public class Intent implements Parcelable, Cloneable{
...
@Override
public Object clone() {
return new Intent(this);
}
...
}
5.总结
- 注意深浅拷贝的问题
基本类型的拷贝为值传递
引用类型的拷贝需要注意深拷贝、浅拷贝
- 必要时进行保护性拷贝