Design Pattern : Singleton

by 18:45:00 0 comments

這是一個很常用的Pattern, 用來確保你的Class 只會有一個 instance. 然後其他地方就可以存取這個 instance 取到同樣的資料.

Class Diagram










Sample Code
/**
 * Created by Gary on 1/25/14.
 */
public class Singleton {
    private static Singleton instance;
    private Singleton(){
        // Initializing
    }
    public static synchronized Singleton getInstance(){
        if(instance == null)
            instance = new Singleton();
        return instance;
    }
    // Other Method...
    public void doSomething(){
     
    }
}

Call
Singleton.getInstance().doSomething();

例子:
這有一個倉庫只會存可樂, 一開始有100罐取完就沒.

倉庫
/**
 * Created by Gary on 1/25/14.
 */
public class WarehouseService {
    private static WarehouseService instance;
    private int coke;
    private WarehouseService(){
        coke = 100;
    }
    public static synchronized WarehouseService getInstance(){
        if(instance == null)
            instance = new WarehouseService();
        return instance;
    }

    // Return true if coke enough.
    public boolean getCoke(int qty){
        if(coke >= qty){
            coke -= qty;
            return true;
        }
        return false;
    }
 
    // Return current coke qty.
    public int getRemain(){
        return coke;
    }
}

取東西的人
/**
 * Created by Gary on 1/25/14.
 */
public class Customer {
    // Get Coke
    public Customer(String name, int cokeQty){
        String status = WarehouseService.getInstance().getCoke(cokeQty) ? "Success" : "Fail";
        System.out.println(name + " get coke " + status);
        System.out.println("Coke remain : " + WarehouseService.getInstance().getRemain());
    }
}

測試
/**
 * Created by Gary on 1/25/14.
 */
public class TestSingleton {
    public static void main(String[] args){
        new Customer("Crab", 10);
        new Customer("Gary" , 90);
        new Customer("Crab" , 10);
    }
}

結果
Crab get coke Success
Coke remain : 90
Gary get coke Success
Coke remain : 0
Crab get coke Fail
Coke remain : 0







0 comments:

Post a Comment