Approach

Step 1: Handle Ambiguity (figure out the question)
Step 2: Define the Core Objects
Step 3: Analyze Relationships
Step 4: Investigate Actions (details)

Design Patterns

Singleton

public class Singleton {
    private static Singleton _instance = null;
    protected Singleton() {}
    public static Singleton getInstance() {
        if(_instance == null) {
            _instance = new Singleton();
        }
        return _instance;
    }
}

_instance是私有的,不可以自己形成实例不可以被引用,用一个getInstance的方法来生成实例和获取实例,也就是封装(encapsulation)。
这段代码在多线程下是不可行的,因为getInstance()是public的,synchronization会有问题,多个线程同时访问这个函数时,会生成多个instance。

利用synchronized和volatile

public class Singleton {
    private volatile static Singleton _instance = null;
    protected Singleton() {}
    public static Singleton getInstance() {
        if(_instance == null) {
            synchronized(Singleton.class) {
                if(_instance == null) {
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
    }
}

Volatile

volatile has the feature of "synchronized".


lulouch13
13 声望6 粉丝