博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java单例模式
阅读量:7171 次
发布时间:2019-06-29

本文共 2308 字,大约阅读时间需要 7 分钟。

hot3.png

在java中,实现单例模式有两种方法:

  1. 将类的构造方法私有化,用一个私有的类变量instance保存类的实例,在加载类时,创建类的实例,并将实例赋给instance;在提供一个公有的静态方法getInstance,用于获取类的唯一实例,该方法直接返回instance。

  2. 将类的构造方法私有化,用一个私有的类变量instance保存类的实例,在加载类时,创建类的实例,并将null赋给instance;在提供一个公有的静态方法getInstance,用于获取类的唯一实例,该方法首先判断instance是否为null,如果为null,则创建实例对象;否则,直接返回instance。

public class SingletonA {	//私有属性	private static int id = 1;	//SingletonA的唯一实例	private static SingletonA instance = new SingletonA();		//将构造函数私有,防止外界构造SingletonA实例	private SingletonA() {	}	/**	 * 获取SingletonA的实例	 */	public static SingletonA getInstance() {		return instance;	}	/**	 * 获取实例的id,synchronized关键字表示该方法是线程同步的,	 * 即任一时刻最多只能有一个线程进入该方法	 * @return	 */	public synchronized int getId() {		return id;	}	/**	 * 将实例的id加1	 */	public synchronized void nextID() {		id++;	}}
public class SingletonB {	//私有属性	private static int id = 1;	//SingletonB的唯一实例	private static SingletonB instance = null;		//将构造函数私有,防止外界构造SingletonB实例	private SingletonB() {	}	//获取SingletonB的唯一实例,同样用synchronized关键字保证某一时刻只有一个线程调用此方法。	public static synchronized SingletonB getInstance() {		//如果instance为空,便创建一个新的SingletonB实例,否则,返回已有的实例		if (instance == null) {			instance = new SingletonB();		}		return instance;	}	public synchronized int getId() {		return id;	}	public synchronized void nextID() {		id++;	}}
/* * 模式名称:单建模式 * 模式特征:只能创建该类的一个实例 * 模式用途:提供一个全局共享类实例 **/public class SingletonTest {	public static void main(String[] args) {		SingletonA a1 = SingletonA.getInstance();		SingletonA a2 = SingletonA.getInstance();		System.out.println("用SingletonA实现单例模式");		System.out.println("调用nextID方法前:");		System.out.println("a1.id=" + a1.getId());		System.out.println("a2.id=" + a2.getId());		a1.nextID();		System.out.println("调用nextID方法后:");		System.out.println("a1.id=" + a1.getId());		System.out.println("a2.id=" + a2.getId());		//SingletonA和SingletonB的区别:前者是在类被加载的时候就创建了实例,		//而后者是在调用getInstance方法时才创建实例。		SingletonB b1 = SingletonB.getInstance();		SingletonB b2 = SingletonB.getInstance();		System.out.println("用SingletonB实现单例模式");		System.out.println("调用nextID方法前:");		System.out.println("b1.id=" + b1.getId());		System.out.println("b2.id=" + b2.getId());		b1.nextID();		System.out.println("调用nextID方法后:");		System.out.println("b1.id=" + b1.getId());		System.out.println("b2.id=" + b2.getId());	}}

转载于:https://my.oschina.net/u/2360415/blog/632430

你可能感兴趣的文章
MySQL中间件之ProxySQL(6):管理后端节点
查看>>
Mathematica 取整函数
查看>>
(转)Awsome Domain-Adaptation
查看>>
利用cwRsync客户端将Windows下文件同步到Linux
查看>>
内联表达式
查看>>
文件相关操作工具类——FileUtils.java
查看>>
原:视频直播技术中的参考技术网页
查看>>
linq教程
查看>>
requests从api中获取数据并存放到mysql中
查看>>
23种设计模式之组合模式(Composite)
查看>>
button按钮点击不刷新(前端交流学习:452892873)
查看>>
安卓 使用Gradle生成正式签名apk文件
查看>>
@Html.Raw()
查看>>
ES6 Proxy
查看>>
图的基本算法(BFS和DFS)
查看>>
Linux时区详解
查看>>
61.node.js开发错误——Error: Connection strategy not found
查看>>
算法逆向第一篇——简单算法逆向
查看>>
机房收费系统数据库概念结构设计
查看>>
NanoJIT
查看>>