设计模式:Android studio 的 live template与单例模式

Android studio 的 live template

单例模式:双重锁懒汉模式(Double Check Lock):

private static $class$ INSTANCE = null;

private $class$() {
}

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

变量class选择 className

单例模式:静态内部类模式staticinner

public class $class${
    private $class$() {
    }

    private static class SingletonInstance {
        private static $class$ INSTANCE = new $class$();
    }

    public static $class$ getInstance() {
        return SingletonInstance.INSTANCE;
    }    
}

变量class选择 fileNameWithoutExtension

android studio 插件 SingletonTest:

在这里插入图片描述在这里插入图片描述


public class Test1 {
    private static Test1 instance;

    private Test1() {
    }

    public static Test1 getInstance() {
        if (instance == null) {
            instance = new Test1();
        }
        return instance;
    }
}


public class Test2 {
    private static Test2 instance;

    private Test2() {
    }

    public static synchronized Test2 getInstance() {
        if (instance == null) {
            instance = new Test2();
        }
        return instance;
    }
}

public class Test3 {
    private static Test3 instance = new Test3();

    private Test3() {
    }

    public static Test3 getInstance() {
        return instance;
    }
}

public class Test4 {

    private static volatile Test4 singleton;

    private Test4() {
    }

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


public class Test5 {

    private Test5() {
    }

    private static class SingletonInstance {
        private static final Test5 INSTANCE = new Test5();
    }

    public static Test5 getInstance() {
        return SingletonInstance.INSTANCE;
    }
}


public enum Test6 {
    INSTANCE;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值