原型设计模式

定义:(拷贝)
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
通过拷贝复制出一个新的对象。(拷贝)最简单的设计模式。又分为浅拷贝和深拷贝

浅拷贝: 浅拷贝,就是类的类对象实例,是没有被拷贝的,他们还是公用一份

  • user代码

public class User implements Cloneable {
    public String userName;
    public int age;
    public Address userAddress;//类的对象实例

    @Override
    protected User clone() throws CloneNotSupportedException {
        return (User) super.clone();
    }

    public static class Address {
        public String addressName;
        public String city;

        public Address(String addressName, String city) {
            this.addressName = addressName;
            this.city = city;
        }


    }
}
  • 测试
public class Client  {
    public static void main(String[] args) {
        User user=new User();
        user.age=18;
        user.userName="Peakmain";
        user.userAddress=new User.Address("安徽合肥","合肥");
        //浅拷贝
        try {
            User copyUser = user.clone();
            //修改地址和名字
            copyUser.userName="Treasure";
            copyUser.userAddress.addressName="上海静安区";
            // 浅拷贝,就是类的类对象实例,是没有被拷贝的,他们还是公用一份
            System.out.print("姓名:"+user.userName+" 地址:"+user.userAddress.addressName+"\n");
            System.out.print("姓名:"+copyUser.userName+" 地址:"+copyUser.userAddress.addressName);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

image.png
深克隆:将地址也进行克隆

  • user代码
public class User implements Cloneable {
    public String userName;
    public int age;
    public Address userAddress;

    @Override
    protected User clone() throws CloneNotSupportedException {
        User user = (User) super.clone();
       user.userAddress= userAddress.clone();
        return user;
    }

    public static class Address implements Cloneable{
        public String addressName;
        public String city;

        public Address(String addressName, String city) {
            this.addressName = addressName;
            this.city = city;
        }

        @Override
        protected Address clone() throws CloneNotSupportedException {
            return (Address) super.clone();
        }
    }
}

image.png

测试代码没有变, 测试代码中 User copyUser = user.clone();调用的是User的克隆所以要在内部调用地址(Address)的克隆

android中运用模式的有

  1. Intent
    比如有三个activity,从activity1启动到activity2,在启动activity3,而数据需要从activity1中传递到activity3中

    activity1:

   Intent intent = new Intent(this,Activity2.class);

        intent.putExtra("Params1","Params1");
        intent.putExtra("Params2","Params2");
        intent.putExtra("Params3","Params3");

        startActivity(intent);

activity2:

     //默认
       /* String Params1 = getIntent().getStringExtra("Params1");
        String Params2 = getIntent().getStringExtra("Params2");
        String Params3 = getIntent().getStringExtra("Params3");
        // 又 new 一个 intent

        // 把参数传递
        Intent intent = new Intent(this,Activity3.class);

        intent.putExtra("Params1",Params1);
        intent.putExtra("Params2",Params2);
        intent.putExtra("Params3",Params3);*/
        //原型设计模式拷贝
        Intent intent = (Intent) getIntent().clone();
        intent.setClass(this, Activity3.class);
        startActivity(intent);

源码

    @Override
    public Object clone() {
        return new Intent(this);
    }
 public Intent(Intent o) {
        //赋值
        this.mAction = o.mAction;
        this.mData = o.mData;
        this.mType = o.mType;
        this.mPackage = o.mPackage;
        this.mComponent = o.mComponent;
        this.mFlags = o.mFlags;
        this.mContentUserHint = o.mContentUserHint;
    }

2 . ArrayList

 ArrayList list=new ArrayList();
// 有很多数据
ArrayList copyList = (ArrayList) list.clone();

源码:

  public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            //数组拷贝
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;//重置修改次数
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

3 . OkHttp

OkHttpClient client = new OkHttpClient();
client.newBuilder();

源码:

Builder(OkHttpClient okHttpClient) {
      this.dispatcher = okHttpClient.dispatcher;
      this.proxy = okHttpClient.proxy;
      this.protocols = okHttpClient.protocols;
      this.connectionSpecs = okHttpClient.connectionSpecs;
      this.interceptors.addAll(okHttpClient.interceptors);
      this.networkInterceptors.addAll(okHttpClient.networkInterceptors);
      this.eventListenerFactory = okHttpClient.eventListenerFactory;
      this.proxySelector = okHttpClient.proxySelector;
      this.cookieJar = okHttpClient.cookieJar;
      this.internalCache = okHttpClient.internalCache;
      this.cache = okHttpClient.cache;
      this.socketFactory = okHttpClient.socketFactory;
      this.sslSocketFactory = okHttpClient.sslSocketFactory;
      this.certificateChainCleaner = okHttpClient.certificateChainCleaner;
      this.hostnameVerifier = okHttpClient.hostnameVerifier;
      this.certificatePinner = okHttpClient.certificatePinner;
      this.proxyAuthenticator = okHttpClient.proxyAuthenticator;
      this.authenticator = okHttpClient.authenticator;
      this.connectionPool = okHttpClient.connectionPool;
      this.dns = okHttpClient.dns;
      this.followSslRedirects = okHttpClient.followSslRedirects;
      this.followRedirects = okHttpClient.followRedirects;
      this.retryOnConnectionFailure = okHttpClient.retryOnConnectionFailure;
      this.connectTimeout = okHttpClient.connectTimeout;
      this.readTimeout = okHttpClient.readTimeout;
      this.writeTimeout = okHttpClient.writeTimeout;
      this.pingInterval = okHttpClient.pingInterval;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常感谢您的提问!以下是一个使用原型设计模式实现深拷贝的示例代码: ``` class Prototype { public: virtual Prototype* clone() = 0; }; class ConcretePrototype : public Prototype { public: ConcretePrototype(int value) : m_value(value) {} Prototype* clone() override { return new ConcretePrototype(m_value); } int getValue() const { return m_value; } private: int m_value; }; int main() { ConcretePrototype* original = new ConcretePrototype(42); ConcretePrototype* clone = dynamic_cast<ConcretePrototype*>(original->clone()); std::cout << "Original value: " << original->getValue() << std::endl; std::cout << "Clone value: " << clone->getValue() << std::endl; delete original; delete clone; return 0; } ``` 在这个示例中,我们定义了一个 `Prototype` 接口,其中包含了一个 `clone()` 方法,用于创建一个与原型对象相同的新对象。然后,我们实现了一个具体的原型类 `ConcretePrototype`,其中包含了一个整型成员变量 `m_value`,并重写了 `clone()` 方法,返回一个新的 `ConcretePrototype` 对象。最后,我们在 `main()` 函数中创建了一个原型对象 `original`,并通过调用 `clone()` 方法创建了一个新的克隆对象 `clone`。 需要注意的是,这里的深拷贝只是一个简单的示例,实际上在实现深拷贝时需要考虑对象的所有成员变量,并递归地进行拷贝。此外,还需要注意内存管理,确保在不需要使用对象时及时释放内存。 希望这个示例能够帮助您理解原型设计模式和深拷贝的实现方式。如果您有任何问题或需要进一步的帮助,请随时提出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值