public class SingletonA
{
//私有属性
private static int id = 1;
//SingletonA的唯一实例
private static SingletonA instance = new SingletonA();
/*
* 将构造函数私有,防止外界构造SingletonA实例
*/
private SingletonA()
{
}
/**
* 获取SingletonA的实例
* @return
*/
public static SingletonA getInstance()
{
return instance;
}
/**
* 获取实例的id,synchronized关键字表示该方法是线程同步的,即任一时刻最多只能
* 有一个线程进入该方法
* @return 返回id属性
*/
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关键字保证某一时刻只有
* 一个线程调用方法
* @return
*/
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());
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());
}
}
分享到:
相关推荐
java Singleton单例模式 java Singleton单例模式
singleton单例模式1
单例模式 Singleton 单例模式线程安全问题和拓展
此示例展示了Qml 的单例模式(类似全局对象,只生成一次实例,可全局使用) surfsky.cnblogs.com
Android Singleton单例模式运用详解
c++ singleton单例模式
本文档,是利用C++来实现设计模式中的,单例模式,里面有内容说明和相关实例代码介绍
C# 23种设计模式之单例模式源码
单例模式的实现,创建,一个文档作为简介
主要介绍了使用设计模式中的Singleton单例模式来开发iOS应用程序的例子,示例代码为传统的Objective-C语言,需要的朋友可以参考下
NULL 博文链接:https://walson.iteye.com/blog/392190
在Java应用中,单例对象能保证在一个...3、有些像交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了,只有使用单例模式,才能保证核心交易服务器独立控制整个流程。 CSDN代码的详细解释。
Singleton pattern单例模式应用
设计模式C++学习之单例模式(Singleton)
单例模式,您能写出几个呢?这个PPT将为你全面阐述5种不同形式的单例模式。
使用"懒汉模式"与"饿汉模式"实现c++的单例模式,并且确保了单例模式的第一次实例化的线程安全,以及程序结束时,单例对象的资源收回,以防内存资源的泄漏
NULL 博文链接:https://linxingliang.iteye.com/blog/1217811
单例模式(Singleton)的6种实现
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个...
单例模式是最简单的一种设计模式,确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例, 本资源提供了用java语言实现简单的单例模式,供初学者参考