單例模式,也就是在系統中只存在一個事例。它的應用還是比較廣泛的,例如產品的功能菜單(功能樹),系統上線以后,它就很少進行修改了,為了提供系統的性能,可以在系統中只存在這樣一個功能菜單事例。這樣單例模式也往往和Caching(緩存)模式同時使用。
package yhp.test.pattern.singleton;

public class TestSingleton {
   
    private static TestSingleton _instance;
    public static TestSingleton getInstance(){
        if(_instance==null)
            _instance=new TestSingleton();
        return _instance;
    }
    private TestSingleton(){}  //保證了不能直接new
    
    private int _x=0;

    public int get_x() {
        return _x;
    }
    public void set_x(int _x) {
        this._x = _x;
    }
   
    public static void main(String[] args) {
        TestSingleton first=TestSingleton.getInstance();
        TestSingleton second=TestSingleton.getInstance();
        first.set_x(4);
        System.out.println("First instance X's Value is:"+first.get_x());                   //輸入:4
        System.out.println("Sesond instance X's Value is:"+second.get_x());         //輸入:4    
    }
}

有點奇怪的是:我在main函數中增加以下代碼:
try{
        TestSingleton test= new TestSingleton(); 
        test.set_x(6);
        System.out.println("new instance X's Value is:"+test.get_x());
}catch(Exception e){
        System.out.println("單例模式對象是不允許被new的!");
}
在eclipse中運行,竟然能夠編譯通過,而且輸出了6,但新建一個類,在main函數中增加相同的代碼,編譯就不能通過了。