温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中怎么实现原型模式

发布时间:2021-06-26 15:55:13 来源:亿速云 阅读:107 作者:Leah 栏目:移动开发

本篇文章给大家分享的是有关Android中怎么实现原型模式,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1.意图
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
热门词汇:克隆  深拷贝 浅拷贝

2.结构图和代码
它的结构图非常简单,我们以Intent为例子:

Android中怎么实现原型模式
Intent的clone方法非常简单:

@Override public Object clone() {      return new Intent(this);  }

返回一个新的Intent对象。
克隆操作分深拷贝和浅拷贝,浅拷贝说白了就是把原对象所有的值和引用直接赋给新对象。深拷贝则不仅把原对象的值赋给新对象,而且会把原对象的引用对象也重新创建一遍再赋给新对象。
我们具体分析一下Intent是浅拷贝还是深拷贝吧:

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;      //下面几个是引用对象被重新创建了,是深拷贝      if (o.mCategories != null) {          this.mCategories = new HashSet<String>(o.mCategories);      }      if (o.mExtras != null) {          this.mExtras = new Bundle(o.mExtras);      }      if (o.mSourceBounds != null) {          this.mSourceBounds = new Rect(o.mSourceBounds);      }  }

这里我们为什么Intent要重写Object的clone方法,就与深拷贝有关。
其实我们查看Object的clone()方法源码和注释,默认的super.clone()用的就是浅拷贝:

/**   * Creates and returns a copy of this {@code Object}. The default   * implementation returns a so-called "shallow" copy: It creates a new   * instance of the same class and then copies the field values (including   * object references) from this instance to the new instance. A "deep" copy,   * in contrast, would also recursively clone nested objects. A subclass that   * needs to implement this kind of cloning should call {@code super.clone()}   * to create the new instance and then create deep copies of the nested,   * mutable objects.   */ protected Object clone() throws CloneNotSupportedException {      if (!(this instanceof Cloneable)) {          throw new CloneNotSupportedException("Class doesn't implement Cloneable");      }        return internalClone((Cloneable) this);  }

这种形式属于简单形式的原型模式,如果需要创建的原型数目不固定,可以创建一个原型管理器,在复制原型对象之前,客户端先在原型管理器中查看
是否存在满足条件的原型对象,如果有,则直接使用,如果没有,克隆一个,这种称作登记形式的原型模式。
适用原型模式可以对客户隐藏产品的具体类,因此减少了客户知道的名字的数目,此外是客户无需改变
原型模式的缺陷是每个原型的子类都必须实现Cloneable接口,这个实现起来有时候比较困难。

以上就是Android中怎么实现原型模式,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI