Tải bản đầy đủ - 0 (trang)
Appendix J. ATM Case Study Code

Appendix J. ATM Case Study Code

Tải bản đầy đủ - 0trang

AppendixJ.ATMCaseStudyCode

SectionJ.1.ATMCaseStudyImplementation

SectionJ.2.ClassATM

SectionJ.3.ClassScreen

SectionJ.4.ClassKeypad

SectionJ.5.ClassCashDispenser

SectionJ.6.ClassDepositSlot

SectionJ.7.ClassAccount

SectionJ.8.ClassBankDatabase

SectionJ.9.ClassTransaction

SectionJ.10.ClassBalanceInquiry

SectionJ.11.ClassWithdrawal

SectionJ.12.ClassDeposit

SectionJ.13.ClassATMCaseStudy

SectionJ.14.Wrap-Up



[Page1527(continued)]



J.1.ATMCaseStudyImplementation

Thisappendixcontainsthecompleteworkingimplementationof

theATMsystemthatwedesignedinthenine"Software

EngineeringCaseStudy"sectionsinChapters1,39and11.The

implementationcomprises655linesofC#code.Weconsider

the11classesintheorderinwhichweidentifiedthemin

Section4.11(withtheexceptionofTRansaction,whichwas

introducedinChapter11asthebaseclassofclasses

BalanceInquiry,WithdrawalandDeposit):

ATM



Screen



Keypad



CashDispenser



DepositSlot



Account



BankDatabase



transaction



BalanceInquiry



Withdrawal



Deposit



WeapplytheguidelinesdiscussedinSection9.17andSection

11.9tocodetheseclassesbasedonhowwemodeledthemin

theUMLclassdiagramsofFig.11.21andFig.11.22.Todevelop

thebodiesofclassmethods,werefertotheactivitydiagrams

presentedinSection6.10andthecommunicationandsequence

diagramspresentedinSection8.14.NotethatourATMdesign

doesnotspecifyalltheprogramlogicandmaynotspecifyall

theattributesandoperationsrequiredtocompletetheATM

implementation.Thisisanormalpartoftheobject-oriented

designprocess.Asweimplementthesystem,wecompletethe

programlogicandaddattributesandbehaviorsasnecessaryto

constructtheATMsystemspecifiedbytherequirements

documentinSection3.10.



[Page1528]

Weconcludethediscussionbypresentingatestharness

(ATMCaseStudyinSectionJ.13)thatcreatesanobjectofclassATM

andstartsitbycallingitsRunmethod.Recallthatweare

developingafirstversionoftheATMsystemthatrunsona

personalcomputerandusesthekeyboardandmonitorto

approximatetheATM'skeypadandscreen.Also,wesimulate

theactionsoftheATM'scashdispenseranddepositslot.We

attempttoimplementthesystemsothatrealhardware

versionsofthesedevicescouldbeintegratedwithoutsignificant

codechanges.[Note:Forthepurposeofthissimulation,we

haveprovidedtwopredefinedaccountsinclassBankDatabase.The

firstaccounthastheaccountnumber12345andthePIN

54321.Thesecondaccounthastheaccountnumber98765and

thePIN56789.Youshouldusetheseaccountswhentestingthe

ATM.]







[Page1528(continued)]



J.2.ClassATM

ClassATM(Fig.J.1)representstheATMasawhole.Lines511

implementtheclass'sattributes.Wedetermineallbutoneof

theseattributesfromtheUMLclassdiagramsofFig.11.21and

Fig.11.22.Line5declarestheboolattributeuserAuthenticated

fromFig.11.22.Line6declaresanattributenotfoundinour

UMLdesignintattributecurrentAccountNumber,whichkeepstrackof

theaccountnumberofthecurrentauthenticateduser.Lines

711declarereference-typeinstancevariablescorrespondingto

theATMclass'sassociationsmodeledintheclassdiagramofFig.

11.21.TheseattributesallowtheATMtoaccessitsparts(i.e.,

itsScreen,Keypad,CashDispenserandDepositSlot)andinteractwith

thebank'saccountinformationdatabase(i.e.,aBankDatabase

object).



FigureJ.1.ClassATMrepresentstheATM.



1//ATM.cs

2//Representsanautomatedtellermachine.

3publicclassATM

4{

5privatebooluserAuthenticated;//trueifuserisauthenticated

6privateintcurrentAccountNumber;//user'saccountnumber

7privateScreenscreen;//referencetoATM'sscreen

8privateKeypadkeypad;//referencetoATM'skeypad

9privateCashDispensercashDispenser;//reftoATM'scashdispenser

10privateDepositSlotdepositSlot;//referencetoATM'sdepositslot

11privateBankDatabasebankDatabase;//reftoaccountinfodatabase

12

13//enumerationthatrepresentsmainmenuoptions

14privateenumMenuOption

15{

16BALANCE_INQUIRY=1,

17WITHDRAWAL=2,

18DEPOSIT=3,

19EXIT_ATM=4

20}//endenumMenuOption

21



[Page1529]

22//parameterlessconstructorinitializesinstancevariables

23publicATM()

24{

25userAuthenticated=false;//userisnotauthenticatedtostart

26currentAccountNumber=0;//nocurrentaccountnumbertostart

27screen=newScreen();//createscreen

28keypad=newKeypad();//createkeypad

29cashDispenser=newCashDispenser();//createcashdispenser

30depositSlot=newDepositSlot();//createdepositslot

31bankDatabase=newBankDatabase();//createaccountinfodatabase

32}//endconstructor

33

34//startATM

35publicvoidRun()

36{

37//welcomeandauthenticateusers;performtransactions

38while(true)//infiniteloop

39{

40//loopwhileuserisnotyetauthenticated

41while(!userAuthenticated)

42{

43screen.DisplayMessageLine("\nWelcome!");

44AuthenticateUser();//authenticateuser

45}//endwhile

46

47PerformTransactions();//forauthenticateduser

48userAuthenticated=false;//resetbeforenextATMsession

49currentAccountNumber=0;//resetbeforenextATMsession

50screen.DisplayMessageLine("\nThankyou!Goodbye!");

51}//endwhile

52}//endmethodRun

53

54//attempttoauthenticateuseragainstdatabase

55privatevoidAuthenticateUser()

56{

57//promptforaccountnumberandinputitfromuser

58screen.DisplayMessage("\nPleaseenteryouraccountnumber:");

59intaccountNumber=keypad.GetInput();

60

61//promptforPINandinputitfromuser

62screen.DisplayMessage("\nEnteryourPIN:");

63intpin=keypad.GetInput();

64

65//setuserAuthenticatedtobooleanvaluereturnedbydatabase

66userAuthenticated=

67bankDatabase.AuthenticateUser(accountNumber,pin);

68

69//checkwhetherauthenticationsucceeded

70if(userAuthenticated)

71currentAccountNumber=accountNumber;//saveuser'saccount#



[Page1530]

72else

73screen.DisplayMessageLine(



74"InvalidaccountnumberorPIN.Pleasetryagain.");

75}//endmethodAuthenticateUser

76

77//displaythemainmenuandperformtransactions

78privatevoidPerformTransactions()

79{

80TransactioncurrentTransaction;//transactionbeingprocessed

81booluserExited=false;//userhasnotchosentoexit

82

83//loopwhileuserhasnotchosenexitoption

84while(!userExited)

85{

86//showmainmenuandgetuserselection

87intmainMenuSelection=DisplayMainMenu();

88

89//decidehowtoproceedbasedonuser'smenuselection

90switch((MenuOption)mainMenuSelection)

91{

92//userchoosestoperformoneofthreetransactiontypes

93caseMenuOption.BALANCE_INQUIRY:

94caseMenuOption.WITHDRAWAL:

95caseMenuOption.DEPOSIT:

96//initializeasnewobjectofchosentype

97currentTransaction=

98CreateTransaction(mainMenuSelection);

99currentTransaction.Execute();//executetransaction

100break;

101caseMenuOption.EXIT_ATM://userchosetoterminatesession

102screen.DisplayMessageLine("\nExitingthesystem...");

103userExited=true;//thisATMsessionshouldend

104break;

105default://userdidnotenteranintegerfrom1-4

106screen.DisplayMessageLine(

107"\nYoudidnotenteravalidselection.Tryagain.");

108break;

109}//endswitch

110}//endwhile

111}//endmethodPerformTransactions

112

113//displaythemainmenuandreturnaninputselection

114privateintDisplayMainMenu()

115{

116screen.DisplayMessageLine("\nMainmenu:");

117screen.DisplayMessageLine("1-Viewmybalance");

118screen.DisplayMessageLine("2-Withdrawcash");

119screen.DisplayMessageLine("3-Depositfunds");

120screen.DisplayMessageLine("4-Exit\n");

121screen.DisplayMessage("Enterachoice:");

122returnkeypad.GetInput();//returnuser'sselection

123}//endmethodDisplayMainMenu



[Page1531]

124

125//returnobjectofspecifiedTransactionderivedclass

126privateTransactionCreateTransaction(inttype)



127{

128Transactiontemp=null;//nullTransactionreference

129

130//determinewhichtypeofTransactiontocreate

131switch((MenuOption)type)

132{

133//createnewBalanceInquirytransaction

134caseMenuOption.BALANCE_INQUIRY:

135temp=newBalanceInquiry(currentAccountNumber,

136screen,bankDatabase);

137break;

138caseMenuOption.WITHDRAWAL://createnewWithdrawaltransaction

139temp=newWithdrawal(currentAccountNumber,screen,

140bankDatabase,keypad,cashDispenser);

141break;

142caseMenuOption.DEPOSIT://createnewDeposittransaction

143temp=newDeposit(currentAccountNumber,screen,

144bankDatabase,keypad,depositSlot);

145break;

146}//endswitch

147

148returntemp;

149}//endmethodCreateTransaction

150}//endclassATM



Lines1420declareanenumerationthatcorrespondstothefour

optionsintheATM'smainmenu(i.e.,balanceinquiry,

withdrawal,depositandexit).Lines2332declareclassATM's

constructor,whichinitializestheclass'sattributes.WhenanATM

objectisfirstcreated,nouserisauthenticated,soline25

initializesuserAuthenticatedtofalse.Line26initializes

currentAccountNumberto0becausethereisnocurrentuseryet.

Lines2730instantiatenewobjectstorepresentthepartsofthe

ATM.RecallthatclassATMhascompositionrelationshipswith

classesScreen,Keypad,CashDispenserandDepositSlot,soclassATMis

responsiblefortheircreation.Line31createsanewBankDatabase.

Asyouwillsoonsee,theBankDatabasecreatestwoAccountobjects

thatcanbeusedtotesttheATM.[Note:IfthiswerearealATM

system,theATMclasswouldreceiveareferencetoanexisting

databaseobjectcreatedbythebank.However,inthis

implementation,weareonlysimulatingthebank'sdatabase,so

classATMcreatestheBankDatabaseobjectwithwhichitinteracts.]



ImplementingtheOperation

TheclassdiagramofFig.11.22doesnotlistanyoperationsfor

classATM.Wenowimplementoneoperation(i.e.,publicmethod)

inclassATMthatallowsanexternalclientoftheclass(i.e.,class

ATMCaseStudy;SectionJ.13)totelltheATMtorun.ATMmethodRun

(lines3552)usesaninfiniteloop(lines3851)torepeatedly

welcomeauser,attempttoauthenticatetheuserand,if

authenticationsucceeds,allowtheusertoperformtransactions.

Afteranauthenticateduserperformsthedesiredtransactions

andexits,theATMresetsitself,displaysagoodbyemessage

andrestartstheprocessforthenextuser.Weuseaninfinite

loopheretosimulatethefactthatanATMappearstorun

continuouslyuntilthebankturnsitoff(anactionbeyondthe

user'scontrol).AnATMusercanexitthesystem,butcannot

turnofftheATMcompletely.



[Page1532]

InsidemethodRun'sinfiniteloop,lines4145causetheATMto

repeatedlywelcomeandattempttoauthenticatetheuseras

longastheuserhasnotbeenauthenticated(i.e.,thecondition

!userAuthenticatedistrue).Line43invokesmethod

DisplayMessageLineoftheATM'sscreentodisplayawelcome

message.LikeScreenmethodDisplayMessagedesignedinthecase

study,methodDisplayMessageLine(declaredinlines1417ofFig.

J.2)displaysamessagetotheuser,butthismethodalso

outputsanewlineafterdisplayingthemessage.Weaddthis

methodduringimplementationtogiveclassScreen'sclientsmore

controlovertheplacementofdisplayedmessages.Line44

invokesclassATM'sprivateutilitymethodAuthenticateUser

(declaredinlines5575)toattempttoauthenticatetheuser.



FigureJ.2.ClassScreenrepresentsthescreenof

theATM.



(Thisitemisdisplayedonpages1534-1535intheprint

version)



1//Screen.cs

2//RepresentsthescreenoftheATM

3usingSystem;

4

5publicclassScreen

6{

7//displaysamessagewithoutaterminatingcarriagereturn

8publicvoidDisplayMessage(stringmessage)

9{

10Console.Write(message);

11}//endmethodDisplayMessage

12

13//displayamessagewithaterminatingcarriagereturn

14publicvoidDisplayMessageLine(stringmessage)

15{

16Console.WriteLine(message);

17}//endmethodDisplayMessageLine

18



[Page1535]

19//displayadollaramount

20publicvoidDisplayDollarAmount(decimalamount)

21{

22Console.Write("{0:C}",amount);

23}//endmethodDisplayDollarAmount

24}//endclassScreen



AuthenticatingtheUser

Werefertotherequirementsdocumenttodeterminethesteps

necessarytoauthenticatetheuserbeforeallowingtransactions

tooccur.Line58ofmethodAuthenticateUserinvokesmethod

DisplayMessageoftheATM'sscreentoprompttheusertoenteran

accountnumber.Line59invokesmethodGetInputoftheATM's

keypadtoobtaintheuser'sinput,thenstoresthisintegerinlocal

variableaccountNumber.MethodAuthenticateUsernextpromptsthe

usertoenteraPIN(line62),andstoresthePINinlocal

variablepin(line63).Next,lines6667attempttoauthenticate



theuserbypassingtheaccountNumberandpinenteredbytheuser

tothebankDatabase'sAuthenticateUsermethod.ClassATMsetsits

userAuthenticatedattributetotheboolvaluereturnedbythis

methoduserAuthenticatedbecomestrueifauthenticationsucceeds

(i.e.,theaccountNumberandpinmatchthoseofanexistingAccount

inbankDatabase)andremainsfalseotherwise.IfuserAuthenticatedis

true,line71savestheaccountnumberenteredbytheuser

(i.e.,accountNumber)intheATMattributecurrentAccountNumber.The

othermethodsofclassATMusethisvariablewheneveranATM

sessionrequiresaccesstotheuser'saccountnumber.If

userAuthenticatedisfalse,lines7374callthescreen's

DisplayMessageLinemethodtoindicatethataninvalidaccount

numberand/orPINwasentered,sotheusermusttryagain.

NotethatwesetcurrentAccountNumberonlyafterauthenticatingthe

user'saccountnumberandtheassociatedPINifthedatabase

cannotauthenticatetheuser,currentAccountNumberremains0.

AftermethodRunattemptstoauthenticatetheuser(line44),if

userAuthenticatedisstillfalse(line41),thewhileloopbody(lines

4145)executesagain.IfuserAuthenticatedisnowtrue,theloop

terminates,andcontrolcontinueswithline47,whichcallsclass

ATM'sprivateutilitymethodPerformTransactions.



PerformingTransactions

MethodPerformTransactions(lines78111)carriesoutanATM

sessionforanauthenticateduser.Line80declareslocalvariable

transaction,towhichweassignaBalanceInquiry,Withdrawalor

DepositobjectrepresentingtheATMtransactioncurrentlybeing

processed.Notethatweuseatransactionvariableheretoallow

ustotakeadvantageofpolymorphism.Also,notethatwename

thisvariableaftertherolenameincludedintheclassdiagram

ofFig.4.21currentTransaction.Line81declaresanotherlocal

variableaboolcalleduserExitedthatkeepstrackofwhetherthe

userhaschosentoexit.Thisvariablecontrolsawhileloop(lines

84110)thatallowstheusertoexecuteanunlimitednumberof



transactionsbeforechoosingtoexit.Withinthisloop,line87

displaysthemainmenuandobtainstheuser'smenuselection

bycallingATMutilitymethodDisplayMainMenu(declaredinlines

114123).Thismethoddisplaysthemainmenubyinvoking

methodsoftheATM'sscreenandreturnsamenuselection

obtainedfromtheuserthroughtheATM'skeypad.Line87stores

theuser'sselection,returnedbyDisplayMainMenu,inlocalvariable

mainMenuSelection.



[Page1533]

Afterobtainingamainmenuselection,method

PerformTransactionsusesaswitchstatement(lines90109)to

respondtotheselectionappropriately.IfmainMenuSelectionis

equaltotheunderlyingvalueofanyofthethreeenummembers

representingtransactiontypes(i.e.,iftheuserchosetoperform

atransaction),lines9798callutilitymethodCreateTransaction

(declaredinlines126149)toreturnanewlyinstantiatedobject

ofthetypethatcorrespondstotheselectedtransaction.

VariablecurrentTransactionisassignedthereferencereturnedby

methodCreateTransaction,thenline99invokesmethodExecuteof

thistransactiontoexecuteit.WediscussTRansactionmethod

ExecuteandthethreeTRansactionderivedclassesshortly.Note

thatweassigntotheTRansactionvariablecurrentTransactionan

objectofoneofthethreetransactionderivedclassessothatwe

canexecutetransactions.Forexample,iftheuserchoosesto

performabalanceinquiry,(MenuOption)mainMenuSelection(line

90)matchesthecaselabelMenuOption.BALANCE_INQUIRY,and

CreateTransactionreturnsaBalanceInquiryobject(lines9798).

Thus,currentTransactionreferstoaBalanceInquiryandinvoking

currentTransaction.Execute()(line99)resultsinBalanceInquiry's

versionofExecutebeingcalledpolymorphically.



CreatingTransactions



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Appendix J. ATM Case Study Code

Tải bản đầy đủ ngay(0 tr)

×