Singleton

Method:

確保一個類別只有一個實體,並且有一個存取方法。

public class Singleton
{
    private static Singleton ins;

    private Singleton() {}
    public static Singleton getInstance()
    {
        if(ins == NULL)
            ins = new Singleton();
        return ins;
    }
}

multi-thread:

確定只有在第一次建立實體時,才進行同步化。

public class Singleton
{
    private static Singleton ins;

    private Singleton() {}
    public static Singleton getInstance()
    {
        if(ins == NULL)
        {
            synchronized(Singleton.class)
            {
                if(ins == NULL)
                    ins = new Singleton();
            }
        }
        return ins;
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License