《Android源码设计模式解析与实战》——原型模式

原型模式用于保护性拷贝对象。注意有浅拷贝和深拷贝。

以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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值