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

目录

0、定义

1、单件模式的一个角色

2、单件模式的UML类图

3、示例代码


0、定义

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

1、单件模式的一个角色

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

2、单件模式的UML类图

3、示例代码

简单的单件模式

java 复制代码
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;
	}

}

使用双重检测的单件模式

java 复制代码
package xyz.jangle.design.singleton;
/**
 * 单例模式,双重检测。
 * @author Administrator
 *
 */
public class SingletonDouble {
	
	private static 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;
	}

}

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

java 复制代码
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;
	}
	

}

客户端(使用)

java 复制代码
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();
		}

	}

}
相关推荐
胡萝卜术6 小时前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序1 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
青禾网络3 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO4 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯4 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术5 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉5 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯7 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆8 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式