第二章、Java设计模式-单例模式(Singleton)

一、简介

1.定义

保证一个类仅有一个实例,并提供一个获取实例的全局访问点(方法|入口)。

2.什么时候用?

顾名思义,我们需要系统中只存在一个实例对象时使用,注意如果同时实现了原型模式,可能会破坏单例。

二、Java实现

1.懒汉模式&饿汉模式

懒汉模式:只有在调用单例模式类提供的入口方法时才实例化对象(这种模式下,只要调用到了该类的静态方法,不管是不是要获取实例,这个单例对象也会被创建)

饿汉模式:未调用单例类的入口方法就已经实例化了对象,不管后面有没有用(像饿汉一样迫不及待 O(∩_∩)O哈哈~)

2.实例

假设我们有一个系统配置类对象,希望整个系统只有一个实例,下面是两种模式的简单实现(多线程中需要注意懒汉模式实现的线程安全,这里未做处理)

public class SystemConfig {
	private static SystemConfig ins = new SystemConfig();

	private SystemConfig() {
	}

	public static SystemConfig newInstance() {
		return ins;
	}
}
public class SystemConfig_Lazy {
	private static SystemConfig_Lazy ins = null;

	private SystemConfig_Lazy() {
	}

	public static SystemConfig_Lazy newInstance() {
		if (ins == null) {
			ins = new SystemConfig_Lazy();
		}
		return ins;
	}
}

猜你喜欢

转载自marionette.iteye.com/blog/2371714