设计模式读书笔记之单例模式(Singleton)
2010-03-28 21:50
393 查看
单例模式:保证一个类只有一个实例,并提供一个全局的访问途经。
特点:
1 该类自己负责保存它自己唯一的实例;
2 该类的构造方法为私有,以保证外部无法调用构造方法来实例化它;
但是如果有多个线程同时访问getInstance,则还是有可能创造出多个实例。改进一下:
package designpattern.singleton; public class Singleton { private static Singleton instance; private Singleton(){} public static Singleton getInstance(){ if(instance==null){ instance = new Singleton(); } return instance; } }
特点:
1 该类自己负责保存它自己唯一的实例;
2 该类的构造方法为私有,以保证外部无法调用构造方法来实例化它;
但是如果有多个线程同时访问getInstance,则还是有可能创造出多个实例。改进一下:
package designpattern.singleton; public class Singleton { private static Singleton instance; private Singleton(){} public static Singleton getInstance(){ if(instance==null){ synchronized(Singleton.class){ if(instance==null){ instance = new Singleton(); } } } return instance; } }
相关文章推荐
- ios设计模式读书笔记----Singleton(单例)
- C# 中的设计模式1:Singleton(学习笔记)
- 设计模式:单例(Singleton)
- java23种设计模式之单例模式(Singleton)
- 设计模式之单例模式Singleton
- 设计模式:单例(Singleton)
- 设计模式读书笔记-----抽象工厂模式
- java设计模式之三单例模式(Singleton)
- 【java设计模式】之 单例(Singleton)模式
- 设计模式---单例模式Singleton(创建型)
- 设计模式-创建型模式之 Singleton(单例)
- Java设计模式之单例模式-Singleton
- 设计模式学习之单件模式(Singleton)
- 深入浅出单例singleton设计模式
- Objective-C设计模式——单例Singleton(对象创建)
- 设计模式C++学习笔记之六(Singleton单例模式)
- Java设计模式一: 单例模式(Singleton)
- Singleton设计模式
- android 源码设计模式解析与实战 读书笔记 1 面向对象的六大原则
- 设计模式读书笔记文档下载