单例模式

一 模式定义
1 某个类只能有一个实例。
2 该类必须自行创建这个实例。
3 该类必须自行向整个系统提供这个实例。

二单例模式举例
1 模式分析


 
2 使用同步线程安全创建单例对象

package com.demo.singleton;

public class Singleton {

	// 类共享实例对象 实例化
	private static Singleton singleton = null;

	// 私有构造方法
	private Singleton() {
		System.out.println("-- this is Singleton!!!");
	}

	// 获得单例方法
	public synchronized static Singleton getInstance() {
		// 直接返回共享对象
		if(singleton == null)
		{
			singleton = new Singleton();
		}
		return singleton;
	}

}

 3 创建一个类全局对象实例作为单例对象

package com.demo.singleton;

/**
 * 单例设计模式
 * 
 * @author
 * 
 */
public class Singleton {

	// 类共享实例对象 实例化
	private static Singleton singleton = new Singleton();

	// 私有构造方法
	private Singleton() {
		System.out.println("-- this is Singleton!!!");
	}

	// 获得单例方法
	public static Singleton getInstance() {
		// 直接返回共享对象
		return singleton;
	}

}

 4 单例客户端代码

package com.demo;

import com.demo.singleton.Singleton;

/**
 * 客户端应用程序
 * 
 * @author
 * 
 */
public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 首先 检验是否能用new操作符创建Singleton对象实例
		Singleton singleton = Singleton.getInstance();
		// 在此获得Singleton对象实例
		Singleton singleton2 = Singleton.getInstance();
		// 比较两个对象是否是同一个对象实例
		if (singleton == singleton2) {
			System.out.println("--这是同一个对象!");
		} else {
			System.out.println("--这是不同的对象!");
		}
	}
}

 运行结果
-- this is Singleton!!!
--这是同一个对象!


三设计模式
1 确保某个类只有一个实例。
2 自行实例化并向整个系统提供这个实例。

原文地址:https://www.cnblogs.com/ainima/p/6331659.html