0x04 - 使程序运行更高效——原型模式

1、定义

用原型实例指定创建的对象的种类,并通过拷贝这些原型创建新的对象

2、使用场景

  • 类初始化很耗费资源(数据、硬件资源等)
  • 通过 new 产生一个新对象需要很繁琐的数据准备或访问权限
  • 一个对象需要供给其他对象访问,而且各个调用者都可能需要修改其值时

3、实现方式

  • 浅拷贝
/**
 * @author Created by Asura on 2018/4/11 14:30.
 */
class WordDoc : Cloneable {
    var text: String? = ""
    var imags = ArrayList()

    fun showDoc() {
        ALog.d("Word Content Start")
        ALog.d("text", "$text", "imags", "$imags")
        ALog.d("asura", "Word Content End")
    }

    public override fun clone(): WordDoc {
        val doc = super.clone() as WordDoc
        doc.text = this.text
        //这里只是浅拷贝
        doc.imags = this.imags
        return doc
    }

    //clone 产生的实例不会调用构造方法
    init {
        ALog.d( "WordDoc 的构造函数")
    }
}
  • 深拷贝
/**
 * @author Created by Asura on 2018/4/11 14:30.
 */
class WordDoc : Cloneable {
    var text: String? = ""
    var imags = ArrayList()

    fun showDoc() {
        ALog.d("Word Content Start")
        ALog.d("text", "$text", "imags", "$imags")
        ALog.d("asura", "Word Content End")
    }

    public override fun clone(): WordDoc {
        val doc = super.clone() as WordDoc
        doc.text = this.text
        //这里 imags 改成深拷贝
        doc.imags = this.imags.clone() as ArrayList
        return doc
    }

    //clone 产生的实例不会调用构造方法
    init {
        ALog.d("WordDoc 的构造函数")
    }
}

4、Demo

Design-Patterns

5、Android 源码中的运用

android.content.Intent
val uri: Uri = Uri.parse("smsto:123456789")
val shareIntent: Intent = Intent(Intent.ACTION_SENDTO, uri)
//克隆副本
var intent: Intent = shareIntent.clone() as Intent

6、优缺点

  • 优点
    原型模式是在内存中二进制流的拷贝,要比直接 new 一个新对象性能好很多

  • 缺点
    直接在内存中拷贝,构造函数不会执行,在实际开发中要注意这个潜在的问题

你可能感兴趣的:(0x04 - 使程序运行更高效——原型模式)