设计模式理解之单例模式

定      义

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. 

Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”


实现方法

An implementation of the singleton pattern must:

● ensure that only one instance of the singleton class ever exists; and

● provide global access to that instance.

Typically, this is done by:

● declaring all constructors of the class to be private; and

● providing a static method that returns a reference to the instance.

The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. 


饿汉式实现[Eager initialization]:

The instance is created when the class  is initialized.

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

● 实例一开始就被创建,以后不再改变,保证了线程安全

● getInstance()方法不需要加synchronize关键字来解决多线程同步的问题

● final 关键字保证了实例不可变,且只会存在一个


懒汉式实现[Lazy initialization]:

A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked.

public final class Singleton {
    private static volatile Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
上面是double-checked locking,下面更普遍的写法:
public class LazySingleton {
    private static volatile LazySingleton instance = null;

    private LazySingleton() {       
    }

    public static synchronized LazySingleton getInstance() {
            if (instance == null) {
                instance = new LazySingleton ();
            }
        return instance;
    }
}

静态内部类方式:

public class Singleton {    
    private static class LazyHolder {    
       private static final Singleton INSTANCE = new Singleton();    
    }    
    private Singleton (){}    
    public static final Singleton getInstance() {    
       return LazyHolder.INSTANCE;    
    }    
}
LazyHolder类会在你需要的时候才会被初始化,而且它不影响Singleton类的其他static成员变量的使用。这个方法是线程安全的并且避免了使用volatile与synchronized。


测      试

public class SingletonTestActivity extends BaseActivity {
    private static final String TAG = "SingletonTestActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Singleton singleton1 = Singleton.getInstance();
        singleton1.setName("Katherine");
        Log.i(TAG, "singleton1.name = " + singleton1.getName());

        Singleton singleton2 = Singleton.getInstance();
        singleton2.setName("Bella");
        Log.i(TAG, "singleton1.name = " + singleton1.getName());
        Log.i(TAG, "singleton2.name = " + singleton2.getName());

        if (singleton1 == singleton2) {
            Log.i(TAG, "singleton1 is the same as singleton2");
        } else {
            Log.i(TAG, "singleton1 isn't the same as singleton2");
        }

        Singleton singleton3 = Singleton.getInstance();
        Log.i(TAG, "singleton1.name = " + singleton1.getName());
        Log.i(TAG, "singleton2.name = " + singleton2.getName());
        Log.i(TAG, "singleton3.name = " + singleton3.getName());
    }
}
测试结果

I/SingletonTestActivity: singleton1.name = Katherine
I/SingletonTestActivity: singleton1.name = Bella
I/SingletonTestActivity: singleton2.name = Bella
I/SingletonTestActivity: singleton1 is the same as singleton2
I/SingletonTestActivity: singleton1.name = Bella
I/SingletonTestActivity: singleton2.name = Bella
I/SingletonTestActivity: singleton3.name = Bella


参考链接:

http://blog.csdn.net/jason0539/article/details/23297037

http://www.iteye.com/topic/652440

http://hukai.me/java-notes-singleton-pattern/

https://en.wikipedia.org/wiki/Singleton_pattern



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值