java设计模式之单例模式
一、单例模式的介绍
Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点
二、单例模式的实现
实现的方式有如下几种:
/**
*
* 单例模式的实现:饿汉式,线程安全 但效率比较低
*/
public class SingletonTest {
private SingletonTest() {
}
private static final SingletonTest instance = new SingletonTest();
public static SingletonTest getInstancei() {
return instance;
}
}
/**
* 单例模式的实现:饱汉式,非线程安全
*
*/
public class SingletonTest {
private SingletonTest() {
}
private static SingletonTest instance;
public static SingletonTest getInstance() {
if (instance == null)
instance = new SingletonTest();
return instance;
}
}
/**
* 线程安全,但是效率非常低
* @author vanceinfo
*
*/
public class SingletonTest {
private SingletonTest() {
}
private static SingletonTest instance;
public static synchronized SingletonTest getInstance() {
if (instance == null)
instance = new SingletonTest();
return instance;
}
}
/**
* 线程安全 并且效率高
*
*/
public class SingletonTest {
private static SingletonTest instance;
private SingletonTest() {
}
public static SingletonTest getIstance() {
if (instance == null) {
synchronized (SingletonTest.class) {
if (instance == null) {
instance = new SingletonTest();
}
}
}
return instance;
}
}
/**
* 静态内部类的方式实现的单列
*/
public class SingletonTest {
public static class Singleton {
public static SingletonTest instance = new SingletonTest();
}
public static SingletonTest getInstance() {
return Singleton.instance;
}
}
/**
* 枚举类型实现的单列
*/
public enum SingletonTest {
INSTANCE;
public static SingletonTest getInstance() {
return INSTANCE;
}
}
分享到:
相关推荐
java设计模式之单例模式
JAVA设计模式之单例模式。 一篇文章带你快速了解!
java设计模式之单例模式,通过例子说明8种单例设计模式。
研磨设计模式之单例模式,牛人精华之作!!!!
java设计模式之单例模式详解,包含例子,详解。
JAVA设计模式之单例模式(完整版)1[定义].pdf
php设计模式之单例模式_.docx
细心整合和单例模式和工厂模式的几种模型,懒汉式,饿汉式,如何并发操作模式,等都有详细讲解
php设计模式之单例模式代码_.docx
设计模式之单例模式,单列模式的几种实现形式,以及其优缺点,还有就是示例,对初步了解单列模式的有所帮助
php设计模式之单例模式实例分析_.docx
PHP设计模式之单例模式__1.docx
单例模式是一种常用的软件设计模式,其定义是单例对象的类只能允许一个实例存在。 许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。 比如在某个服务器程序中,该服务器的配置信息存放...
JAVA设计模式之单例模式(完整版)[归类].pdf
目录 单例模式的概念 单例模式的要点 单例模式类图 单例模式归类 单例模式的应用场景 单例模式解决的问题 单例模式的实现方式 单例模式实现方式对比 单例模式的概念 单例模式,顾名思义就是只有一个实例,并且由它...