設計模式,單元測試,重構是今天的程序員必須掌握的程序設計技術.
一、什麼是單例模式?
在我們的Java應用程序中,隨着應用程序的運行會創建出很多對象。但有時候我們希望在創建某類對象時,無論創建多少次該類對象只有一份在內存中。這就是單例模式。如果我們要實現單例模式首先要保證構造函數私有化,即不允許用戶隨意調用我本類的構造函數,因爲只要通過new操作創建對象,必定要在堆中開闢空間,這樣就無法實現單例了。
二、單例模式的實現
public class Singleton{
private static Singleton single=null;
private Singleton(){}
public static Singleton getSingleton(){
if(single==null){
single=new Singleton();
}
return single;
}
}
設計模式的書都太厚了,看一遍都累個半死,所以我有了這個想法,用最簡單的語言和最簡單的代碼來說明設計模式.
案例描述:
街頭 銀行取款機一次只可以一個人,用一張卡站它前面提款.
程序:
/*
* 銀行提款機 ATM
*/
package com.singleton;
public class ATMCash {
private static ATMCash instance;
private String creditCard;
private ATMCash() {
}
/**
* 保證只有一個人一張卡在使用提款機
*/
public static synchronized ATMCash getInstance() {
if (instance == null)
instance = new ATMCash();
return instance;
}
public String getMoney() {
return creditCard;
}
//插入ATM磁卡
public void setCard(String card) {
creditCard = card;
}
//取出ATM磁卡
public void getCard() {
creditCard = null;
}
}
/*
* 提款
*/
package com.singleton;
public class Singleton {
public static void main(String[] args) {
//------------下面是我的取款過程--------------
ATMCash myCash = ATMCash.getInstance(); //來一個人取款
myCash.setCard("我的銀行卡");//插入磁卡
System.out.println("我取錢用的是 :" +myCash.getMoney()); //取款
//myCash.getCard(); //取回磁卡
//------------下面是你取款過程----------------
ATMCash yourCash = ATMCash.getInstance(); //來一個人取款
System.out.println("你取錢用的是 :" + yourCash.getMoney()); //取款
}
}