优点:
- 性能优良
- 逃避构造函数的约束
缺点:
- 由于使用原型模式复制对象时不会调用类的构造方法,所以原型模式无法和单例模式组合使用,因为原型类需要将clone方法的作用域修改为public类型,那么单例模式的条件就无法满足了。
- 对象不能声明为final
应用场景:
- 资源优化场景
- 性能和安全要求的场景
注意:
- (拷贝 int ,long,char等) (不拷贝 String,内部数组,引用对象)
/**
* 原型模式
*
* @(拷贝 int ,long,char等) (不拷贝 String,内部数组,引用对象)
* @ final与clone()方法互斥
*
* @author Administrator
*
*/
public class Brother implements Cloneable {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private int age;
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 void exect() {
System.out.println("姓名:" + getName() + " 年龄=" + getAge());
}
private ArrayList<String> mData = new ArrayList<>();
public void setValue(String value) {
mData.add(value);
}
public ArrayList<String> getValue() {
return mData;
}
@SuppressWarnings("unchecked")
@Override
public Brother clone() {
// TODO Auto-generated method stub
Brother object = null;
try {
object = (Brother) super.clone();
// object.mData = (ArrayList<String>) this.mData.clone(); //深拷贝
} catch (CloneNotSupportedException e) {
// TODO: handle exception
System.out.println(e);
}
return object;
}
}
调用
// 原型模式
Brother brother = new Brother();
brother.setValue("哥哥");
Brother brother1 = brother.clone();
brother1.setValue("弟弟");
System.out.println("list = "+brother.getValue());
System.out.println("list = "+brother1.getValue());
//输出结果 浅拷贝
list = [哥哥, 弟弟]
list = [哥哥, 弟弟]
//输出结果 深拷贝
list = [哥哥]
list = [哥哥, 弟弟]