1. 程式人生 > 其它 >CMake版本低升級高版本

CMake版本低升級高版本

技術標籤:設計模式設計模式單例模式

1 單例模式

JVM提供全域性唯一的物件,例項化一次,由類自身進行例項化。

2 實現方式

2.1 懶載入

package designpattern.singleton;

/**
* @description 單例:懶載入
* @author xindaqi
* @since 2021-02-10 15:24:43
*/
public class LazyLoading {

    private static LazyLoading instance;

    private LazyLoading() {}

    private static LazyLoading getInstance
() { if(instance == null) { instance = new LazyLoading(); } return instance; } }

2.2 預載入

package designpattern.singleton;

/**
* @description 單例模式:預載入
* @author xindaqi
* @since 2021-02-10 17:04:04
*/
public class Preloading {

    private static Preloading instance =
new Preloading(); private Preloading() {} private Preloading getInstance() { return instance; } }

2.3 雙檢鎖

package designpattern.singleton;

/**
* @description 單例模式:雙檢鎖
* @author xindaqi
* @since 2021-02-10 17:54:03
*/
public class DoubleCheckLocking {

    private volatile static
DoubleCheckLocking instance; private DoubleCheckLocking() {} public static DoubleCheckLocking getInstance() { if(null == instance) { synchronized(DoubleCheckLocking.class) { if(null == instance) { instance = new DoubleCheckLocking(); } } } return instance; } }

2.4 內部靜態類

package designpattern.singleton;

/**
* @description 單例模式:靜態內部類
* @author xindaqi
* @since 2021-02-10 20:02:51
*/
public class StaticInside {

    private static class StaticInsideHandler {
        private static final StaticInside INSTANCE = new StaticInside();
    }

    private StaticInside() {}

    public static final StaticInside getInstance() {
        return StaticInsideHandler.INSTANCE;
    }
    
}

2.5 列舉

package designpattern.singleton;

/**
* @description 單例模式:列舉
* @author xindaqi
* @since 2021-02-10 20:09:34
*/
public enum EnumSingleton {

    INSTANCE;

    public void singletonEnumMethod() {}
    
}

3 小結

  • 單例即單個例項化物件
  • 執行緒安全的情況下,JVM內只有一個例項
  • 例項化由類自身完成