這是一個很常用的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(){
}
}
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
今天早上突然想到 Excel 中 Sum 或者其他基本函數中,有些引數的數量其實不固定,那如果要在自定義的 Function 中要怎麼使用?
於是就整理在這兒了 ( ̄ー ̄)
於是就整理在這兒了 ( ̄ー ̄)
Just a note, enjoy it!
Function,所謂的自訂函數。
在Function裡寫入自己想要的功能,而後在工作表(Sheet)裡就能自由運用該函數。
接下來的範例,在Function裡寫入可以抓取該模組(Module)裡全域變數的相關程式碼,就可以在工作表(Sheet)裡使用。
在Function裡寫入自己想要的功能,而後在工作表(Sheet)裡就能自由運用該函數。
接下來的範例,在Function裡寫入可以抓取該模組(Module)裡全域變數的相關程式碼,就可以在工作表(Sheet)裡使用。



