java中单例设计模式分析

单例设计模式分为两种:懒汉式和饿汉式

单例设计模式构成:

1、私有的静态的成员变量类本身的对象

2、私有的构造方法

3、公有的静态的获得该类创建出来的对象

// 懒汉式
class Singleton {
	private static Singleton singleton = null;

	private Singleton() {
	}

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

// 饿汉式
class Singleton2 {
	private static Singleton2 singleton = new Singleton2();

	private Singleton2() {
	}

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

而多线程在单例设计模式中的应用:

// 懒汉式
class Singleton {
	private static Singleton singleton = null;

	private Singleton() {
	}

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

// 饿汉式
class Singleton2 {
	private static Singleton2 singleton = new Singleton2();

	private Singleton2() {
	}

	public static synchronized Singleton2 getInstance() {
		return singleton;
	}
}

单例设计模式的应用:

1、网站的计数器,一般也是采用单例模式实现,否则难以同步。

2、程序的日志文件,一般都采用单例模式实现,这是由于共享的日志文件一直处于打开状态,因为只能有一个实例去操作,否则内容不好追加。

3、web应用的配置文件的读取,一般也应用单例模式,这个是由于配置文件是共享的资源。

4、数据库连接池的设计一般也是采用单例模式,因为数据库连接是一种数据库资源。数据库软件系统中使用数据库连接池,主要是节省打开或者关闭数据库连接所引起的效率损耗,这种效率上的损耗还是非常昂贵的,因为何用单例模式来维护,就可以大大降低这种损耗。

5、多线程的线程池的设计一般也是采用单例模式,这是由于线程池要方便对池中的线程进行控制。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值