大話設計模式 - 第31章 (1/2)

大B:“我給你舉個例子來說明吧!”

小A:“嗯。好的。”

大B:“讓我們建立一個應用:1、接受客戶的詳細資料(賬戶、地址和信用卡信息)2、驗證輸극的信息3、保存輸극的信息到相應的文件中。這個應用有三個類:Account、Address和CreditCard。每一個類都有自己的驗證和保存數據的方法。”

Listing1:AccountClass

publicclassAccount{

StringfirstName;

StringlastName;

finalStringACCOUNTDATAFILE=“AccountData.txt”;

publicAccount(Stringfname,Stringlname){

firstName=fname;

lastName=lname;

}

publicbooleanisValid(){

}

publicbooleansave(){

FileUtilfutil=newFileUtil();

StringdataLine=getLastName()+,+getFirstName();

returnfutil.writeToFile(ACCOUNTDATAFILE,dataLine,true,true);

}

publicStringgetFirstName(){

returnfirstName;

}

publicStringgetLastName(){

returnlastName;

}

}

Listing2:AddressClass

publicclassAddress{

Stringaddress;

Stringcity;

Stringstate;

finalStringADDRESSDATAFILE=“Address.txt”;

publicAddress(Stringadd,Stringcty,Stringst){

address=add;

city=cty;

state=st;

}

publicbooleanisValid(){

if(getState().trim().length()(2)

returnfalse;

returntrue;

}

publicbooleansave(){

FileUtilfutil=newFileUtil();

StringdataLine=getAddress()+,“+getCity()+”,+getState();

returnfutil.writeToFile(ADDRESSDATAFILE,dataLine,true,true);

}

publicStringgetAddress(){

returnaddress;

}

publicStringgetCity(){

returncity;

}

publicStringgetState(){

returnstate;

}

}

Listing3:CreditCardClass

publicclassCreditCard{

StringcardType;

StringcardNumber;

StringcardExpDate;

finalStringCCDATAFILE=“CC.txt”;

publicCreditCard(StringccType,StringccNumber,

StringccExpDate){

cardType=ccType;

cardNumber=ccNumber;

cardExpDate=ccExpDate;

}

publicbooleanisValid(){

return(getCardNumber().trim().length()……16);

}

return(getCardNumber().trim().length()……15);

}

return(getCardNumber().trim().length()……16);

}

returnfalse;

}

publicbooleansave(){

FileUtilfutil=newFileUtil();

StringdataLine=getCardType()+,“+getCardNumber()+”,+getCardExpDate();

returnfutil.writeToFile(CCDATAFILE,dataLine,true,true);

}

publicStringgetCardType(){

returncardType;

}

publicStringgetCardNumber(){

returncardNumber;

}

上一章|目錄|下一章