单例模式--java实现

文章来源:软件秘笈--设计模式那点事

单例模式(Singleton Pattern)

定义:确保某一个类只有一个实例,而且向整个系统提供这个实例的获取方法。

使用单例模式的要点:

1、某各类只能有一个实例。

2、该类必须自己创建这个实例。

3、该类必须向系统提供这个实例。

模式结构图:


代码:

第一部分;线程安全的单例对象

//单例模式-------线程安全
package com.singleton;

public class Singleton {
	//类共享实例对象
	private static Singleton singleton = null;
	//私有构造方法
	private Singleton(){
		System.out.println("This is Singleton!");
	}
	
	//synchronized保证线程安全,避免竞争
	public synchronized static Singleton getInstance(){
		//判断共享对象是否为null,如果是则new一个
		if(singleton == null){
			singleton = new Singleton();
		}
		return singleton;
	}
	

}

package com;

import com.singleton.Singleton;

//测试程序
public class Client {
	public static void main(String [] args){
		//获取single实例
		Singleton singleton = Singleton.getInstance();
		Singleton singleton2 = Singleton.getInstance();
		
		if(singleton == singleton2){
			System.out.println("这是同一个对象");
		}
		else{
			System.out.println("这不是同一个对象");			
		}
	}

}

二、类全局对象实例作为单例对象

//创建一个类全局对象实例作为单例对象
package com.singleton;

public class Singleton1 {
	//类共享实例对象实例化
	private static Singleton1 singleton = new Singleton1();
	
	private Singleton1(){
		System.out.println("This is Singleton1!");
	}
	
	public static Singleton1 getInstance(){
		return singleton;
	}
	

}

package com;

import com.singleton.Singleton1;

public class Client1 {
	public static void main(String [] args){
		//获取single实例
				Singleton1 singleton = Singleton1.getInstance();
				Singleton1 singleton2 = Singleton1.getInstance();
				
				if(singleton == singleton2){
					System.out.println("这是同一个对象");
				}
				else{
					System.out.println("这不是同一个对象");			
				}
		}
}


发布了35 篇原创文章 · 获赞 8 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章