OOP Design
文章目录
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".
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论