设计模式—常用的设计模式介绍

设计模式—常用的设计模式介绍

1.单例模式(Singleton)

简单点说,就是一个应用程序中,某个类的实例对象只有一个,你没有办法去new,因为构造器是被private修饰的,一般通过getInstance()的方法来获取它们的实例。getInstance()的返回值是一个对象的引用,并不是一个新的实例

  • 1>懒汉式写法(线程不安全)
/**
 * 懒汉式(线程不安全)
 */
public class Singleton {
    private static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }

}
  • 2>懒汉式写法(线程安全)
/**
 * 懒汉式(线程安全)
 */
public class Singleton2 {
    private static Singleton2 singleton;

    private Singleton2() {
    }

    /**
     * 使用了synchronized关键字
     * @return
     */
    public static synchronized Singleton2 getInstance() {
        if (singleton == null) {
            singleton = new Singleton2();
        }
        return singleton;
    }
}

  • 3>饿汉式写法
/**
 * 饿汉式
 */
public class Singleton3 {
    private static Singleton3 singleton = new Singleton3();

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        return singleton;
    }
}

  • 4>静态内部类写法
/**
 * 静态内部类写法
 */
public class Singleton4 {

    /**
     * 静态内部类
     */
    private static class SingletonHolder{
        private static final Singleton4 instance = new Singleton4();
    }

    private Singleton4() {
    }

    public static Singleton4 getInstance() {
        return SingletonHolder.instance;
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值