java design pattern--singleton pattern

      java design pattern -- singleton pattern

 singleton design pattern

Singleton is a creational mode, which means that a class adopts the Singleton mode. After the class is created, only one instance can be generated for external access, and a global access point is provided.

The core knowledge points are as follows:

(1)  Make the constructor of a class that adopts the singleton design pattern private ( modified by private) .

(2)  The instantiated object of the class is generated inside it, and it is encapsulated into a private static type.

(3)  Define a static method to return an instance of the class.

 

/**

 * Method one

 * Implementation of singleton mode: hungry , thread-safe but inefficient

 */  

publicclass SingletonTest {   

    // define a private constructor

    private SingletonTest() {  

    }  

    // Set its own instance object as a property , and add Static and final modifiers

    privatestaticfinal SingletonTest instance = new SingletonTest();    

    // static method returns an instance of this class

    publicstatic SingletonTest getInstancei() {   

        return instance;  

    }  

  

}

 

The first method is the legendary hungry mode. The
advantages are: it is relatively simple to write, and there is no multi-threaded synchronization problem, which avoids the performance problems caused by synchronization ; the
disadvantage is: when the class SingletonTest is loaded, it will initialize static instance , the static variable is created and allocated memory space. Since then, the static instance object has been occupying this memory (even if you have not used the instance), when the class is unloaded, the static variable is destroyed, and Frees occupied memory, so memory is consumed under certain conditions.

 

/**  

 * Method 2

 * Implementation of singleton mode: full-bodied , non-thread-safe   

 *   

 */  

public class SingletonTest {

    // 定义私有构造方法(防止通过 new SingletonTest()去实例化)

    private SingletonTest() {   

    }   

    //定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)

    private static SingletonTest instance;   

    //定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题)

    public static SingletonTest getInstance() {   

        if (instance ==null)   

            instance =new SingletonTest();   

        return instance;   

    }   

}

 

方法二就是传说的中的饱汉模式
优点是:写起来比较简单,当类SingletonTest被加载的时候,静态变量staticinstance未被创建并分配内存空间,当getInstance方法第一次被调用时,初始化instance变量,并分配内存,因此在某些特定条件下会节约了内存;
缺点是:并发环境下很可能出现多个SingletonTest实例。

 

/**  

 *方法三

 *单例模式的实现:饱汉式,线程安全简单实现   

 *   

 */  

public class SingletonTest {

    //定义私有构造方法(防止通过new SingletonTest()去实例化)

    private SingletonTest() {   

    }   

    //定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)

    private static SingletonTest instance;   

    //定义一个静态的方法(调用时再初始化SingletonTest,使用synchronized避免多线程访问时,可能造成重的复初始化问题)

    public static synchronized  SingletonTest getInstance() {   

        if (instance ==null)   

            instance =new SingletonTest();   

        return instance;   

    }   

}

 

方法三为方法二的简单优化
优点是:使用synchronized关键字避免多线程访问时,出现多个SingletonTest实例。
缺点是:同步方法频繁调用时,效率略低。

 

        /**  

          *方法四

          *单例模式最优方案

           *线程安全  并且效率高  

          *  

           */  

public class SingletonTest {    

    //定义一个私有构造方法

    private SingletonTest() {
     

    }   

    //定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)

    private static volatile SingletonTest instance;  

    //定义一个共有的静态方法,返回该类型实例

    public static SingletonTest getIstance() { 
        // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率)

        if (instance ==null) {
            //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)

            synchronized (SingletonTest.class) {
                //未初始化,则初始instance变量

                if (instance ==null) {

                    instance =new SingletonTest();   

                }   

            }   

        }   

        return instance;   

    }   

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325572010&siteId=291194637