head first 设计模式——(单件模式)
2016-09-24 16:39
211 查看
//未处理 public class Singleton { private static Singleton singleton; private Singleton(){} public static Singleton getInstance(){ if(singleton == null){ singleton = new Singleton(); } return singleton; } //其他方法 } //多线程 public class Singleton_1 { private static Singleton_1 singleton; private Singleton_1(){} //synchronized迫使每个线程在进入这个方法之前,要先等候别的线程离开该方法。 //也就是说,不会有两个线程可以同时进入这个方法。 //但这样耗费不较大。 public static synchronized Singleton_1 getInstance(){ if(singleton == null){ singleton = new Singleton_1(); } return singleton; } //其他方法 } //急切创建实例; public class Singleton_2 { private static Singleton_2 singleton = new Singleton_2() ; private Singleton_2(){} public static Singleton_2 getInstance(){ return singleton; } //其他方法 } // 双重检查加锁; /** * 此方式仅适用于 jdk 1.4以后的版本 * @author dxq * */ public class Singleton_3 { private volatile static Singleton_3 singleton; private Singleton_3(){} public static Singleton_3 getInstance(){ if(singleton == null){ synchronized (Singleton_3.class){ if(singleton == null){ singleton = new Singleton_3(); } } } return singleton; } //其他方法 }
相关文章推荐
- Head First 设计模式 (五) 单件模式(Singleton pattern) C++实现
- head first 设计模式学习随笔(5)----单件模式
- 《Head First 设计模式》学习笔记——单件(例)模式
- <Head First 设计模式>:单件模式:Singleton
- 《Head First 设计模式》单件模式
- Head First 设计模式(5):单件模式
- 单件(单例)模式(Head First 设计模式复习笔记)
- Head First 设计模式学习笔记 —— 单件模式
- Head First 设计模式——单件模式(Singleton Pattern)
- Head First 设计模式(五)单件模式
- Head First 设计模式之单件模式(Singleton Pattern)
- Head First 设计模式 (五) 单件模式(Singleton pattern) C++实现
- Head First--设计模式 单件模式 独一无二的对象
- 学习head first 设计模式之单件模式
- 设计模式-单件
- 设计模式学习(三)单件模式-生成器模式
- .Net设计模式学习笔记(二):单件模式(Singleton Pattern)
- .NET设计模式:单件模式(Singleton Pattern)
- .NET设计模式-单件模式(Singleton Pattern)
- [整理]C#面向对象设计模式纵横谈(2):Singleton单件(创建型模式)