java单例模式的几种写法_设计模式之单例模式的几种写法——java

对于设计模式的使用场景和好处,之前有介绍一篇,今天主要是单例模式的编写方式,直接看代码吧

单例模式之饿汉模式,不会懒加载。线程安全

/**

* @Author wangtao

* @Description 单例模式之饿汉模式,不会懒加载。线程安全

* @Date 2019-5-22 12:32

* @优点 线程安全,简单易实现

* @缺点 在进行类加载的时候就创建好实例,会占用内存

**/

class SingletonHungry{

//私有构造函数

private SingletonHungry(){}

//创建实例

private static final SingletonHungry singletonHungry=new SingletonHungry();

//提供获取公有方法

public static SingletonHungry getInstance(){

return singletonHungry;

}

}

单例模式之懒汉模式,会懒加载。线程不安全

/**

* @Author wangtao

* @Description 单例模式之懒汉模式,会懒加载。线程不安全

* @Date 2019-5-22 12:32

* @优点

* @缺点

**/

class SingletonLazy {

//私有构造函数

private SingletonLazy() {}

//创建实例

private static SingletonLazy singletonLazy;

//提供获取公有方法

public static SingletonLazy getInstance() {

if(singletonLazy==null){

singletonLazy=new SingletonLazy();

}

return singletonLazy;

}

}

单例模式之懒汉模式,会懒加载。线程安全,同步方法

/**

* @Author wangtao

* @Description 单例模式之懒汉模式,会懒加载。线程安全,同步方法

* @Date 2019-5-22 12:32

* @优点

* @缺点

**/

class SingletonLazyThread {

//私有构造函数

private SingletonLazyThread() {}

//创建实例

private static SingletonLazyThread singletonLazyThread;

//提供获取公有方法

public static synchronized SingletonLazyThread getInstance() {

if(singletonLazyThread==null){

singletonLazyThread=new SingletonLazyThread();

}

return singletonLazyThread;

}

}

单例模式之懒汉模式,会懒加载。线程安全,同步代码块(文本称为:双重锁)

/**

* @Author wangtao

* @Description 单例模式之懒汉模式,会懒加载。线程安全,同步代码块(文本称为:双重锁)

* @Date 2019-5-22 12:32

* @优点

* @缺点

**/

class SingletonLazyThread2 {

//私有构造函数

private SingletonLazyThread2() {}

//创建实例

private static SingletonLazyThread2 singletonLazyThread2;

//提供获取公有方法

public static SingletonLazyThread2 getInstance() {

synchronized(SingletonLazyThread2.class){

if(singletonLazyThread2==null){

singletonLazyThread2=new SingletonLazyThread2();

}

}

return singletonLazyThread2;

}

}

单例模式之饿汉模式优化,会懒加载。线程安全,使用静态内部类

/**

* @Author wangtao

* @Description 单例模式之饿汉模式优化,会懒加载。线程安全,使用静态内部类

* @Date 2019-5-22 12:32

* @优点 懒加载,在进行加载内部类的时候才会初始化对象,线程安全,是饿汉模式的优化,避免了直接的实例化占用内存空间的问题

* @缺点 只使用于静态的方法

**/

class SingletonInnerClass{

//私有构造函数

private SingletonInnerClass() {}

//创建实例

private static class SingletonInner{

private static final SingletonInnerClass singletonInnerClass =new SingletonInnerClass();

}

//提供获取公有方法

public static SingletonInnerClass getInstance() {

return SingletonInner.singletonInnerClass;

}

}

单例模式之枚举,不会懒加载。线程安全,自动序列化

/**

* @Author wangtao

* @Description 单例模式之枚举,不会懒加载。线程安全,自动序列化

* @Date 2019-5-22 12:32

* @优点

* @缺点

**/

enum SingletonEnum{

INSTANCE;

public void say(){

System.out.println("枚举类的方法");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值