一、

1.The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

2.

3.

二、例子一:线程不安全

 package headfirst.designpatterns.singleton.chocolate;

 public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
private static ChocolateBoiler uniqueInstance; private ChocolateBoiler() {
empty = true;
boiled = false;
} public static ChocolateBoiler getInstance() {
if (uniqueInstance == null) {
System.out.println("Creating unique instance of Chocolate Boiler");
uniqueInstance = new ChocolateBoiler();
}
System.out.println("Returning instance of Chocolate Boiler");
return uniqueInstance;
} public void fill() {
if (isEmpty()) {
empty = false;
boiled = false;
// fill the boiler with a milk/chocolate mixture
}
} public void drain() {
if (!isEmpty() && isBoiled()) {
// drain the boiled milk and chocolate
empty = true;
}
} public void boil() {
if (!isEmpty() && !isBoiled()) {
// bring the contents to a boil
boiled = true;
}
} public boolean isEmpty() {
return empty;
} public boolean isBoiled() {
return boiled;
}
}

三、加上synchronized

直接在getInstance()方法中加上synchronized虽然线程安全,但得不尝失。因为理想的情况是只在第一次访问getInstance时才需要同步,以后的访问不用同步,因为已经有了instance了

 package headfirst.designpatterns.singleton.threadsafe;

 public class Singleton {
private static Singleton uniqueInstance; // other useful instance variables here private Singleton() {} public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
} // other useful methods here
public String getDescription() {
return "I'm a thread safe Singleton!";
}
}

四、用饿汉式解决线程安全(用static ,JVM会在任何线程访问前初始化变量)

 package headfirst.designpatterns.singleton.stat;

 public class Singleton {
private static Singleton uniqueInstance = new Singleton(); private Singleton() {} public static Singleton getInstance() {
return uniqueInstance;
} // other useful methods here
public String getDescription() {
return "I'm a statically initialized Singleton!";
}
}

Using this approach, we rely on the JVM to create the unique instance of the Singleton when the class is loaded. The JVM guarantees that the instance will be created before any thread accesses the static uniqueInstance variable.

五、用双重检查

 package headfirst.designpatterns.singleton.dcl;

 //
// Danger! This implementation of Singleton not
// guaranteed to work prior to Java 5
// public class Singleton {
private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}

With double-checked locking, we first check to see if an instance is created, and if not, THEN we synchronize. This way, we only synchronize the first time through, just what we want.

The volatile keyword ensures that multiple threads handle the uniqueInstance variable correctly when it is being initialized to the Singleton instance.

六、

1.

Q: What about class loaders?
I heard there is a chance that two class loaders could each end up with their own instance of Singleton.A: Yes, that is true as each class loader defines a namespace. If you have two or more classloaders, you can load the same class multiple times (once in each classloader). Now, if that class happens to be a Singleton, then since we have more than one version of the class, we also have more than one instance of the Singleton. So, if you are using multiple classloaders
and Singletons, be careful. One way around this problem is to specify the classloader yourself.

2.

I still don’t totally understand why global variables are worse than a Singleton.
A: In Java, global variables are basically static references to objects.There are a couple of disadvantages to using global variables in this manner. We’ve already mentioned one: the issue of lazy versus eager instantiation. But we need to keep in mind the intent of the pattern: to ensure only one instance of a class exists and to provide global access. A
global variable can provide the latter,but not the former. Global variables also tend to encourage developers
to pollute the namespace with lots of global references to small objects.Singletons don’t encourage this in the same way, but can be abused nonetheless.

 

HeadFirst设计模式之单例模式的更多相关文章

  1. Delphi 设计模式:《HeadFirst设计模式》Delphi2007代码---单例模式之ChocolateBoiler[转]

     1  2{<HeadFirst设计模式>之单例模式 }  3{ 编译工具: Delphi2007 for win32 }  4{ E-Mail : guzh-0417@163.com   ...

  2. headfirst设计模式(5)—工厂模式体系分析及抽象工厂模式

    先编一个这么久不写的理由 上周我终于鼓起勇气翻开了headfirst设计模式这本书,看看自己下一个设计模式要写个啥,然后,我终于知道我为啥这么久都没写设计模式了,headfirst的这个抽象工厂模式, ...

  3. 设计模式之单例模式(Singleton)

    设计模式之单例模式(Singleton) 设计模式是前辈的一些经验总结之后的精髓,学习设计模式可以针对不同的问题给出更加优雅的解答 单例模式可分为俩种:懒汉模式和饿汉模式.俩种模式分别有不同的优势和缺 ...

  4. GJM : C#设计模式(1)——单例模式

    感谢您的阅读.喜欢的.有用的就请大哥大嫂们高抬贵手"推荐一下"吧!你的精神支持是博主强大的写作动力以及转载收藏动力.欢迎转载! 版权声明:本文原创发表于 [请点击连接前往] ,未经 ...

  5. java设计模式之单例模式(几种写法及比较)

    概念: Java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例.饿汉式单例.登记式单例. 单例模式有以下特点: 1.单例类只能有一个实例. 2.单例类必须自己创建 ...

  6. 每天一个设计模式-4 单例模式(Singleton)

    每天一个设计模式-4 单例模式(Singleton) 1.实际生活的例子 有一天,你的自行车的某个螺丝钉松了,修车铺离你家比较远,而附近的五金店有卖扳手:因此,你决定去五金店买一个扳手,自己把螺丝钉固 ...

  7. 设计模式之单例模式的简单demo

    /* * 设计模式之单例模式的简单demo */ class Single { /* * 创建一个本类对象. * 和get/set方法思想一样,类不能直接调用对象 * 所以用private限制权限 * ...

  8. 设计模式之单例模式——Singleton

                        设计模式之单例模式--Singleton 设计意图: 保证类仅有一个实例,并且可以供应用程序全局使用.为了保证这一点,就需要这个类自己创建自己的对象,并且对外有 ...

  9. 10月27日PHP加载类、设计模式(单例模式和工厂模式)、面向对象的六大原则

    加载类可以使用include.require.require_once三种中的任意一种,每个关键字都有两种方法,但是这种方法的缺点是需要加载多少个php文件,就要写多少个加载类的方法.一般也就需要加载 ...

随机推荐

  1. Map的三种遍历方式

    对于Map的三种方式遍历 1.keySet() 2.values() 3.entrySet()三种方式得到Set之后,都可以使用 foreach或者iterator, 不能使用for,因为数据结构决定 ...

  2. @override

    目录 用处 作用 注意   用处: 继承抽象类,必须实现抽象方法,方法上要加@override 实现接口时,必须实现接口里定义的方法,方法上要加@override         作用: 可以检查方法 ...

  3. spring junit参数

    备忘,以后有时间再写点东西吧.其实自己就没有开始写过. blog地址:http://www.cnblogs.com/shizhongtao/p/3342174.html //spring 配置的路径, ...

  4. jQuery学习-----(一)JQuery的'$'符号用法

    1.jQuery的三种$() 1)$()可以是$(expresion),即css选择器.Xpath或html元素,也就是通过上述表达式来匹配目标元素.   比如:$("a")构造的 ...

  5. WinForms 小型HTML服务器

    最近教学,使用到了Apache和IIS,闲着无聊,有种想自己写个小服务器的冲动. 在网上找了半天的资料,最后终于搞定了,测试可以访问.效果图如下: 因为只是处理简单的请求,然后返回请求的页面,所以没有 ...

  6. c# 类型初始值设定项引发异常

    今天使用VS2010编译c#程序,编译顺利通过,点击运行启动程序,弹框提示如题错误.断点调试,程序甚至都没有进入main函数!!查阅网上资料,几种分析如下(1)反射机制 (2)app.config文件 ...

  7. php 随机显示图片的函数(实例)

    转自:http://www.jbxue.com/article/12695.html   发布:thatboy   来源:Net     [大 中 小] 本文分享一个php实现的随机显示图片的函数,可 ...

  8. php判断服务器是否支持Gzip压缩功能

    Gzip可以压缩网页大小从而达到加速打开网页的速度,目前主流的浏览器几乎都支持这个功能,但开启Gzip是需要服务器支持的,在这里我们简单的使用php来判断服务器是否支持Gzip功能. 新建一个php类 ...

  9. 安装 php 转

    一 安装 php 命令: sudo apt-get install libapache2-mod-php5 php5 出现了如下错误: 按照方案一 解决了此问题. 一下 from   http://w ...

  10. 《WPF程序设计指南》读书笔记——第5章 Stack与Wrap

    1.StackPanel面板 using System; using System.Windows; using System.Windows.Input; using System.Windows. ...