设计模式:17、单件模式(单例模式)

目录

0、定义

1、单件模式的一个角色

2、单件模式的UML类图

3、示例代码


0、定义

        保证一个类仅有一个实例,并提供一个访问它的全局访问点。

1、单件模式的一个角色

  • 单件类(Singleton):单件类只可以创建出一个实例。

2、单件模式的UML类图

3、示例代码

简单的单件模式

package xyz.jangle.design.singleton;
/**
 * 单件模式
 * @author Administrator
 *
 */
public class Singleton {
	
	private static Singleton uniqueInstance;
	
	private Singleton() {
		System.out.println("简单的单例模式");
	};
	
	public static synchronized Singleton getInstance() {
		if(uniqueInstance==null) {
			uniqueInstance= new Singleton();
		}
		return uniqueInstance;
	}

}

使用双重检测的单件模式

package xyz.jangle.design.singleton;
/**
 * 单例模式,双重检测。
 * @author Administrator
 *
 */
public class SingletonDouble {
	
	private static volatile SingletonDouble uniqueInstance;
	
	private SingletonDouble() {
		System.out.println("单例模式,使用双重检测");
	}
	
	public static SingletonDouble getInstance() {
		if(uniqueInstance==null) {
			synchronized (SingletonDouble.class) {
				if(uniqueInstance==null) {
					uniqueInstance = new SingletonDouble();
				}
			}
		}
		return uniqueInstance;
	}

}

使用静态内部类的单件模式

package xyz.jangle.design.singleton;
/**
 * 使用静态内部类实现单例模式
 * @author Administrator
 *
 */
public class SingletonInnerStatic {
	
	private SingletonInnerStatic() {
		System.out.println("静态内部类的单例模式");
	};
	
	private static class SingletonInner {
		private static final SingletonInnerStatic INSTANCE = new SingletonInnerStatic();
	}
	
	public static SingletonInnerStatic getInstance() {
		return SingletonInner.INSTANCE;
	}
	

}

客户端(使用)

package xyz.jangle.design.singleton;

public class AppMain17 {

	public static void main(String[] args) {
		
		for (int i = 0; i < 10; i++) {
			new Thread(()->{ 
				System.out.println("获取单例模式");
				Singleton instance = Singleton.getInstance();
				System.out.println("成功获取单例"+instance);
			}).start();
		}
		
		for (int i = 0; i < 10; i++) {
			new Thread(()->{ 
				System.out.println("获取单例模式");
				SingletonDouble instance = SingletonDouble.getInstance();
				System.out.println("成功获取单例"+instance);
			}).start();
		}
		
		for (int i = 0; i < 10; i++) {
			new Thread(()->{ 
				System.out.println("获取单例模式");
				SingletonInnerStatic instance = SingletonInnerStatic.getInstance();
				System.out.println("成功获取单例"+instance);
			}).start();
		}

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值