1. 程式人生 > 實用技巧 >Intel Sysret --- CVE-2012-0217

Intel Sysret --- CVE-2012-0217

顧名思義,單例模式就是要求只有一個實體物件。

單例模式分為懶漢式和餓漢式

餓漢式:一開始就建立物件,執行緒安全,但是如果用不到這個物件,會造成浪費

懶漢式:要的時候才建立,不會造成浪費,但是會有執行緒安全的問題.

餓漢式和懶漢式都是私有化建構函式,不讓外面能夠直接new 物件.

餓漢式

private static Hungry instance = new Hungry();

    private Hungry(){}


    public Hungry getInstance(){
        return instance;
    }

懶漢不安全式

public class
LazyUnSafe { private LazyUnSafe instance; public LazyUnSafe getInstance(){ if(instance == null){ instance = new LazyUnSafe(); } return instance; } }

懶漢安全式

public class LazySafe {

    private LazySafe instance;

    private LazySafe(){}

    public
LazySafe getInstance() { if(instance == null){ synchronized (LazySafe.class){ if(instance == null){ instance = new LazySafe(); } return instance; } } return instance; } }