单例模式 (Singleton Pattern)


1、懒汉式

/* 单例模式(懒汉式) */
public class Agent {
    
    private static Agent myAgent = null;
    
    private Agent() {
        // 构造方法私有化
    }
    
    public static Agent getInstance() {
        if(myAgent == null) {
            myAgent = new Agent();
        }
        return myAgent;
    }
    
}

2、饿汉式

/* 单例模式(饿汉式) */
public class Agent {
    
    private static Agent myAgent = new Agent();
    
    private Agent() {
        // 构造方法私有化
    }
    
    public static Agent getInstance() {
        return myAgent;
    }
    
}