原型模式用于保护性拷贝对象。注意有浅拷贝和深拷贝。
以Java代码为例:
public class Test {
private static User a = null;
public static void setUser(){
a = new User();
a.age = 18;
a.name = "Peter";
a.address = new Address("USA","New York");
}
public static User getUser(){
//返回的结果不是原始对象a,而是a的拷贝
//保障了a不会被篡改
return a.clone();
}
public static void main(String[] args) {
setUser();
getUser().address.city = "Seattle";
System.out.println(a.address.city);
}
}
class User implements Cloneable{
public int age;
public String name;
public Address address;
@Override
protected User clone() {
User user = null;
try{
//深拷贝
user = (User)super.clone();
user.address = address.clone();
} catch (CloneNotSupportedException e){
e.printStackTrace();
}
return user;
}
}
class Address implements Cloneable{
public String country;
public String city;
public Address(String aCountry, String aCity, ) {
country = aCountry;
city = aCity;
}
@Override
protected Address clone() {
Address address = null;
try{
address = (Address)super.clone();
}catch (CloneNotSupportedException e){
e.printStackTrace();
}
return address;
}
}
如果不采取保护性拷贝的话,原始User对象a的city参数就会被篡改为Seattle。
原型模型在Android源码中的体现:
@Override
public Object clone(){
return new Intent(this);
}
public Intent(Intent o){
this.mAction = o.mAction;
this.mData = o.mData;
... ...
if(o.mCategories != null){
this.mCategories = new ArraySet<String>(o.mCategories);
}
if(o.mExtras != null){
this.mExtras = new Bundle(o.mExtras);
}
... ...
}
这里,Android使用的new的形式构造对象。
使用示例如下:
Intent shareIntent = new Intent(Intent.ACTION_SENDTO, uri);
shareIntent.putExtra("sms_body", "The SMS text");
Intent intent = (Intent)shareIntent.clone();
startActivity(intent);