Design Patterns in Android development-a detailed explanation of the singleton pattern:
1. Characteristics of the singleton mode:
(1). Ensure that there is only one instance of a class
(2). Provides a global access point that can be accessed to him.
(3). The constructor is declared private, thereby preventing the creation of objects outside the class
2. Type:
(1). A hungry man single-case mode
(2). Lazy single-case mode
3. Code Analysis:
(1). A hungry man single-case mode:
//类加载的时候对象就实例化了。 privatestaticnew Single(); publicstaticgetInstance() { return mSingle; //缺点:不能保证有其他的方式导致类加载,这时候对象实例化没有达到延迟加载的效果
(2). Lazy Singleton mode: (thread-safe), (second use this way)
publicstaticgetInstance2() { synchronized (Single.class) { ifnull) { new Single(); } } return mSingle2; } //这个类只有一个实例,在多线程的时候也是创建一个实例。同一时间内只有一个线程调用这个方法,若有多个线程同时访问这个方法的话,其它的线程必须等待。//如果没有这个关键字,在多线程的时候就会创建两个或者多个实例.这种方式效率比较低。
(3). Internal class Mode: (Recommended Use this way)
privatestaticclass SingleHolder { privatestaticnew Single(); }publicstaticgetInstance03() { return//保证了对象初始化的时候只有一个线程。类加载的时候也没有主动初始化对象。只是在调用getInstance03()方法的时候加载了SingleHolder。达到了延迟加载的效果。
Design Patterns in Android development-a detailed explanation of the singleton pattern