黑马程序员--懒汉式和饿汉式单例设计模式
2014-10-17 10:37
127 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
饿汉式:
public class Singleton{
private static Singleton singleton = new Singleton ();
private Singleton (){}
public Singleton getInstance(){return singletion;}
}
懒汉式1:
public class Singleton{
private static Singleton singleton = null;
public static synchronized getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
懒汉式2
public class LazySignleton {
private static LazySignleton INSTANCE = null;
//私有化构造子,阻止外部直接实例化对象
private LazySignleton(){
}
// 获取类的单例实例
public static LazySignleton getInstance(){
if(INSTANCE == null){
synchronized (LazySignleton.class) {
if(INSTANCE == null){
INSTANCE = new LazySignleton();
}
}
}
return INSTANCE;
}
}
比较:
饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变
懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的
推荐使用第一种
饿汉式:
public class Singleton{
private static Singleton singleton = new Singleton ();
private Singleton (){}
public Singleton getInstance(){return singletion;}
}
懒汉式1:
public class Singleton{
private static Singleton singleton = null;
public static synchronized getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
懒汉式2
public class LazySignleton {
private static LazySignleton INSTANCE = null;
//私有化构造子,阻止外部直接实例化对象
private LazySignleton(){
}
// 获取类的单例实例
public static LazySignleton getInstance(){
if(INSTANCE == null){
synchronized (LazySignleton.class) {
if(INSTANCE == null){
INSTANCE = new LazySignleton();
}
}
}
return INSTANCE;
}
}
比较:
饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变
懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的
推荐使用第一种
相关文章推荐
- 黑马程序员-面向对象-06天-6(单例设计模式-饿汉式,懒汉式)
- 黑马程序员-单例设计模式:懒汉式和饿汉式
- 黑马程序员-单例设计模式:“饿汉式”和“懒汉式”
- 黑马程序员--单例设计模式的笔记(懒汉式,饿汉式)
- 黑马程序员——java小结_007_单例设计模式(懒汉式、饿汉式)
- 黑马程序员一单例设计模式的饿汉式与懒汉式以及加锁的情况
- Java模式设计之单例模式, 接上篇【饿汉式,懒汉式】
- java设计单例模式【饿汉式和懒汉式】
- Java 单例设计模式(懒汉式 饿汉式)
- 设计模式——单例模式(饿汉式、懒汉式)
- 单例设计模式(懒汉式和饿汉式区别)
- JAVA面向对象知识点总结(4)— 单例设计模式:饿汉式、懒汉式
- 单例设计模式(饿汉式和懒汉式)
- JAVA单例设计模式(饿汉式和懒汉式的区别)
- Java---15---单例设计模式:---饿汉式和懒汉式
- 设计模式——单例模式(饿汉式、懒汉式)
- 设计模式--单例模式(一)懒汉式和饿汉式
- Java_设计模式_单例设计模式(饿汉式和懒汉式)
- Java设计模式中的单例模式的懒汉式和饿汉式
- java二十三种设计模式----(二)单例设计模式 :“懒汉式”与“饿汉式”的区别 为什么通常使用饿汉式