[读书笔记] Android 源码设计模式解析与实战 第2版

https://www.jianshu.com/p/49baca8fd52e

面向对象的六大原则

  • 单一职责原则(一个类只做一个事情)

一、单例模式:

1. 饿汉模式(不推荐)

private static Test sInstance = new Test();

private Test() {
}

public static Test getInstance() {
    return sInstance;
}

缺点:多线程下无法保证单例对象唯一

2. 懒汉模式(不推荐)

private static Test sInstance;

private Test() {
}

public static synchronized Test getInstance() {
    if (sInstance == null) {
        sInstance = new Test();
    }
    return sInstance;
}

优点:保证单例对象唯一(多线程下)
缺点:每次调用都会同步,造成不必要的同步开销

3. DCL(一般用这种方式可以满足需求)

private volatile static Test sInstance;

private Test() {
}

public static Test getInstance() {
    if (sInstance == null) {
        synchronized (Test.class) {
            if (sInstance == null) {
                sInstance = new Test();
            }
        }
    }
    return sInstance;
}

优点:需要时才初始化,能保证线程安全
缺点:第一次加载较慢,也可能出现失败的情况

4. 静态内部类模式(推荐)

private Test() {
}

public static Test getInstance() {
    return Holder.sInstance;
}

private static class Holder {
    private static final Test sInstance = new Test();
}

优点:在第一次调用的时候才会导致sInstance初始化,可以保证线程安全,对象唯一,同时延迟了初始化

二、Builder模式

优点:良好的封装性
缺点:会产生多余的Builder对象, 消耗内存

三、原型模式

即实现Cloneable接口, 调用clone方法, 通过复制这些原型创建新的对象。
用于使用new产生对象很复杂或者需要访问权限的情况

  • 浅拷贝
    复制类字段引用原始类的字段, 修改会影响原始类
  • 深拷贝
    在拷贝对象时, 对引用类型的字段也采用拷贝的形式
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值