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

Appendix G. ATM Case Study Code

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

AppendixG.ATMCaseStudyCode

SectionG.1.ATMCaseStudyImplementation

SectionG.2.ClassATM

SectionG.3.ClassScreen

SectionG.4.ClassKeypad

SectionG.5.ClassCashDispenser

SectionG.6.ClassDepositSlot

SectionG.7.ClassAccount

SectionG.8.ClassBankDatabase

SectionG.9.ClassTransaction

SectionG.10.ClassBalanceInquiry

SectionG.11.ClassWithdrawal

SectionG.12.ClassDeposit

SectionG.13.TestProgramATMCaseStudy.cpp

SectionG.14.Wrap-Up



[Page1285(continued)]



G.1.ATMCaseStudyImplementation

Thisappendixcontainsthecompleteworkingimplementationof

theATMsystemthatwedesignedinthe"SoftwareEngineering

CaseStudy"sectionsfoundattheendsofChapters17,9and

13.Theimplementationcomprises877linesofC++code.We

considertheclassesintheorderinwhichweidentifiedthemin

Section3.11:

ATM



Screen



Keypad



CashDispenser



DepositSlot



Account



BankDatabase



transaction



BalanceInquiry



Withdrawal



Deposit



WeapplytheguidelinesdiscussedinSection9.12andSection

13.10tocodetheseclassesbasedonhowwemodeledthemin

theUMLclassdiagramsofFig.13.28andFig.13.29.Todevelop

thedefinitionsofclasses'memberfunctions,werefertothe

activitydiagramspresentedinSection5.11andthe

communicationandsequencediagramspresentedinSection

7.12.NotethatourATMdesigndoesnotspecifyalltheprogram

logicandmaynotspecifyalltheattributesandoperations

requiredtocompletetheATMimplementation.Thisisanormal

partoftheobject-orienteddesignprocess.Asweimplementthe

system,wecompletetheprogramlogicandaddattributesand

behaviorsasnecessarytoconstructtheATMsystemspecified

bytherequirementsdocumentinSection2.8.



[Page1286]

WeconcludethediscussionbypresentingaC++program

(ATMCaseStudy.cpp)thatstartstheATMandputstheotherclasses

inthesysteminuse.Recallthatwearedevelopingafirst

versionoftheATMsystemthatrunsonapersonalcomputer

andusesthecomputer'skeyboardandmonitortoapproximate

theATM'skeypadandscreen.Wealsoonlysimulatetheactions

oftheATM'scashdispenseranddepositslot.Weattemptto

implementthesystem,however,sothatrealhardwareversions

ofthesedevicescouldbeintegratedwithoutsignificantchanges

inthecode.







[Page1286(continued)]



G.2.ClassATM

ClassATM(Figs.G.1G.2)representstheATMasawhole.Figure

G.1containstheATMclassdefinition,enclosedin#ifndef,#define

and#endifpreprocessordirectivestoensurethatthisdefinition

onlygetsincludedonceinaprogram.Wediscusslines611

shortly.Lines1617containthefunctionprototypesforthe

class'spublicmemberfunctions.TheclassdiagramofFig.13.29

doesnotlistanyoperationsforclassATM,butwenowdeclarea

publicmemberfunctionrun(line17)inclassATMthatallowsan

externalclientoftheclass(i.e.,ATMCaseStudy.cpp)totelltheATMto

run.Wealsoincludeafunctionprototypeforadefault

constructor(line16),whichwediscussshortly.



[Page1287]

FigureG.1.DefinitionofclassATM,which

representstheATM.

(Thisitemisdisplayedonpage1286intheprintversion)



1//ATM.h

2//ATMclassdefinition.Representsanautomatedtellermachine.

3#ifndefATM_H

4#defineATM_H

5

6#include"Screen.h"//Screenclassdefinition

7#include"Keypad.h"//Keypadclassdefinition

8#include"CashDispenser.h"//CashDispenserclassdefinition

9#include"DepositSlot.h"//DepositSlotclassdefinition

10#include"BankDatabase.h"//BankDatabaseclassdefinition

11classTransaction;//forwarddeclarationofclassTransaction

12

13classATM

14{

15public:

16ATM();//constructorinitializesdatamembers

17voidrun();//starttheATM



18private:

19booluserAuthenticated;//whetheruserisauthenticated

20intcurrentAccountNumber;//currentuser'saccountnumber

21Screenscreen;//ATM'sscreen

22Keypadkeypad;//ATM'skeypad

23CashDispensercashDispenser;//ATM'scashdispenser

24DepositSlotdepositSlot;//ATM'sdepositslot

25BankDatabasebankDatabase;//accountinformationdatabase

26

27//privateutilityfunctions

28voidauthenticateUser();//attemptstoauthenticateuser

29voidperformTransactions();//performstransactions

30intdisplayMainMenu()const;//displaysmainmenu

31

32//returnobjectofspecifiedTransactionderivedclass

33Transaction*createTransaction(int);

34};//endclassATM

35

36#endif//ATM_H



Lines1925ofFig.G.1implementtheclass'sattributesas

privatedatamembers.Wedetermineallbutoneofthese

attributesfromtheUMLclassdiagramsofFig.13.28andFig.

13.29.NotethatweimplementtheUMLBooleanattribute

userAuthenticatedinFig.13.29asabooldatamemberinC++

(line19).Line20declaresadatamembernotfoundinourUML

designanintdatamembercurrentAccountNumberthatkeepstrackof

theaccountnumberofthecurrentauthenticateduser.Wewill

soonseehowtheclassusesthisdatamember.

Lines2124createobjectstorepresentthepartsoftheATM.

RecallfromtheclassdiagramofFig.13.28thatclassATMhas

compositionrelationshipswithclassesScreen,Keypad,CashDispenser

andDepositSlot,soclassATMisresponsiblefortheircreation.Line

25createsaBankDatabase,withwhichtheATMinteractstoaccess

andmanipulatebankaccountinformation.[Note:Ifthiswerea

realATMsystem,theATMclasswouldreceiveareferencetoan

existingdatabaseobjectcreatedbythebank.However,inthis

implementationweareonlysimulatingthebank'sdatabase,so

classATMcreatestheBankDatabaseobjectwithwhichitinteracts.]

Notethatlines610#includetheclassdefinitionsofScreen,Keypad,

CashDispenser,DepositSlotandBankDatabasesothattheATMcanstore



objectsoftheseclasses.

Lines2830and33containfunctionprototypesforprivateutility

functionsthattheclassusestoperformitstasks.Wewillsee

howthesefunctionsservetheclassshortly.Notethatmember

functioncreateTransaction(line33)returnsatransactionpointer.

Toincludetheclassnametransactioninthisfile,wemustat

leastincludeaforwarddeclarationofclasstransaction(line11).

Recallthataforwarddeclarationtellsthecompilerthataclass

exists,butthattheclassisdefinedelsewhere.Aforward

declarationissufficienthere,asweareusingtransactiononlyas

areturntypeifwewerecreatinganactualTRansactionobject,we

wouldneedto#includethefulltransactionheaderfile.



ATMClassMember-FunctionDefinitions

FigureG.2containsthemember-functiondefinitionsforclass

ATM.Lines37#includetheheaderfilesrequiredbythe

implementationfileATM.cpp.NotethatincludingtheATMheader

fileallowsthecompilertoensurethattheclass'smember

functionsaredefinedcorrectly.Thisalsoallowsthemember

functionstousetheclass'sdatamembers.

Line10declaresanenumnamedMenuOptionthatcontains

constantscorrespondingtothefouroptionsintheATM'smain

menu(i.e.,balanceinquiry,withdrawal,depositandexit).Note

thatsettingBALANCE_INQUIRYto1causesthesubsequent

enumerationconstantstobeassignedthevalues2,3and4,as

enumerationconstantvaluesincrementby1.



[Page1290]

FigureG.2.ATMclassmember-function

definitions.



(Thisitemisdisplayedonpages1287-1290intheprint

version)



1//ATM.cpp

2//Member-functiondefinitionsforclassATM.

3#include"ATM.h"//ATMclassdefinition

4#include"Transaction.h"//Transactionclassdefinition

5#include"BalanceInquiry.h"//BalanceInquiryclassdefinition

6#include"Withdrawal.h"//Withdrawalclassdefinition

7#include"Deposit.h"//Depositclassdefinition

8

9//enumerationconstantsrepresentmainmenuoptions

10enumMenuOption{BALANCE_INQUIRY=1,WITHDRAWAL,DEPOSIT,EXIT};

11

12//ATMdefaultconstructorinitializesdatamembers

13ATM::ATM()

14:userAuthenticated(false),//userisnotauthenticatedtostart

15currentAccountNumber(0)//nocurrentaccountnumbertostart

16{

17//emptybody

18}//endATMdefaultconstructor

19

20//startATM

21voidATM::run()

22{

23//welcomeandauthenticateuser;performtransactions

24while(true)

25{

26//loopwhileuserisnotyetauthenticated

27while(!userAuthenticated)

28{

29screen.displayMessageLine("\nWelcome!");

30authenticateUser();//authenticateuser

31}//endwhile

32

33performTransactions();//userisnowauthenticated

34userAuthenticated=false;//resetbeforenextATMsession

35currentAccountNumber=0;//resetbeforenextATMsession

36screen.displayMessageLine("\nThankyou!Goodbye!");

37}//endwhile

38}//endfunctionrun

39

40//attempttoauthenticateuseragainstdatabase

41voidATM::authenticateUser()

42{

43screen.displayMessage("\nPleaseenteryouraccountnumber:");

44intaccountNumber=keypad.getInput();//inputaccountnumber

45screen.displayMessage("\nEnteryourPIN:");//promptforPIN

46intpin=keypad.getInput();//inputPIN

47

48//setuserAuthenticatedtoboolvaluereturnedbydatabase

49userAuthenticated=



50bankDatabase.authenticateUser(accountNumber,pin);

51

52//checkwhetherauthenticationsucceeded

53if(userAuthenticated)

54{

55currentAccountNumber=accountNumber;//saveuser'saccount#

56}//endif

57else

58screen.displayMessageLine(

59"InvalidaccountnumberorPIN.Pleasetryagain.");

60}//endfunctionauthenticateUser

61

62//displaythemainmenuandperformtransactions

63voidATM::performTransactions()

64{

65//localpointertostoretransactioncurrentlybeingprocessed

66Transaction*currentTransactionPtr;

67

68booluserExited=false;//userhasnotchosentoexit

69

70//loopwhileuserhasnotchosenoptiontoexitsystem

71while(!userExited)

72{

73//showmainmenuandgetuserselection

74intmainMenuSelection=displayMainMenu();

75

76//decidehowtoproceedbasedonuser'smenuselection

77switch(mainMenuSelection)

78{

79//userchosetoperformoneofthreetransactiontypes

80caseBALANCE_INQUIRY:

81caseWITHDRAWAL:

82caseDEPOSIT:

83//initializeasnewobjectofchosentype

84currentTransactionPtr=

85createTransaction(mainMenuSelection);

86

87currentTransactionPtr->execute();//executetransaction

88

89//freethespaceforthedynamicallyallocatedTransaction

90deletecurrentTransactionPtr;

91

92break;

93caseEXIT://userchosetoterminatesession

94screen.displayMessageLine("\nExitingthesystem...");

95userExited=true;//thisATMsessionshouldend

96break;

97default://userdidnotenteranintegerfrom1-4

98screen.displayMessageLine(

99"\nYoudidnotenteravalidselection.Tryagain.");

100break;

101}//endswitch

102}//endwhile

103}//endfunctionperformTransactions

104

105//displaythemainmenuandreturnaninputselection



106intATM::displayMainMenu()const

107{

108screen.displayMessageLine("\nMainmenu:");

109screen.displayMessageLine("1-Viewmybalance");

110screen.displayMessageLine("2-Withdrawcash");

111screen.displayMessageLine("3-Depositfunds");

112screen.displayMessageLine("4-Exit\n");

113screen.displayMessage("Enterachoice:");

114returnkeypad.getInput();//returnuser'sselection

115}//endfunctiondisplayMainMenu

116

117//returnobjectofspecifiedTransactionderivedclass

118Transaction*ATM::createTransaction(inttype)

119{

120Transaction*tempPtr;//temporaryTransactionpointer

121

122//determinewhichtypeofTransactiontocreate

123switch(type)

124{

125caseBALANCE_INQUIRY://createnewBalanceInquirytransaction

126tempPtr=newBalanceInquiry(

127currentAccountNumber,screen,bankDatabase);

128break;

129caseWITHDRAWAL://createnewWithdrawaltransaction

130tempPtr=newWithdrawal(currentAccountNumber,screen,

131bankDatabase,keypad,cashDispenser);

132break;

133caseDEPOSIT://createnewDeposittransaction

134tempPtr=newDeposit(currentAccountNumber,screen,

135bankDatabase,keypad,depositSlot);

136break;

137}//endswitch

138

139returntempPtr;//returnthenewlycreatedobject

140}//endfunctioncreateTransaction



Lines1318defineclassATM'sconstructor,whichinitializesthe

class'sdatamembers.WhenanATMobjectisfirstcreated,no

userisauthenticated,soline14usesamemberinitializertoset

userAuthenticatedtofalse.Likewise,line15initializes

currentAccountNumberto0becausethereisnocurrentuseryet.

ATMmemberfunctionrun(lines2138)usesaninfiniteloop(lines



2437)torepeatedlywelcomeauser,attempttoauthenticate

theuserand,ifauthenticationsucceeds,allowtheuserto

performtransactions.Afteranauthenticateduserperformsthe

desiredtransactionsandchoosestoexit,theATMresetsitself,



displaysagoodbyemessagetotheuserandrestartsthe

process.Weuseaninfiniteloopheretosimulatethefactthat

anATMappearstoruncontinuouslyuntilthebankturnsitoff

(anactionbeyondtheuser'scontrol).AnATMuserhasthe

optiontoexitthesystem,butdoesnothavetheabilitytoturn

offtheATMcompletely.

Insidememberfunctionrun'sinfiniteloop,lines2731causethe

ATMtorepeatedlywelcomeandattempttoauthenticatethe

useraslongastheuserhasnotbeenauthenticated(i.e.,

!userAuthenticatedistrue).Line29invokesmemberfunction

displayMessageLineoftheATM'sscreentodisplayawelcome

message.LikeScreenmemberfunctiondisplayMessagedesignedin

thecasestudy,memberfunctiondisplayMessageLine(declaredin

line13ofFig.G.3anddefinedinlines2023ofFig.G.4)

displaysamessagetotheuser,butthismemberfunctionalso

outputsanewlineafterdisplayingthemessage.Wehaveadded

thismemberfunctionduringimplementationtogiveclass

Screen'sclientsmorecontrolovertheplacementofdisplayed

messages.Line30ofFig.G.2invokesclassATM'sprivateutility

functionauthenticateUser(lines4160)toattempttoauthenticate

theuser.



[Page1291]

Werefertotherequirementsdocumenttodeterminethesteps

necessarytoauthenticatetheuserbeforeallowingtransactions

tooccur.Line43ofmemberfunctionauthenticateUserinvokes

memberfunctiondisplayMessageoftheATM'sscreentopromptthe

usertoenteranaccountnumber.Line44invokesmember

functiongetInputoftheATM'skeypadtoobtaintheuser'sinput,

thenstorestheintegervalueenteredbytheuserinalocal

variableaccountNumber.MemberfunctionauthenticateUsernext

promptstheusertoenteraPIN(line45),andstoresthePIN

inputbytheuserinalocalvariablepin(line46).Next,lines

4950attempttoauthenticatetheuserbypassingthe

accountNumberandpinenteredbytheusertothebankDatabase's



authenticateUsermemberfunction.ClassATMsetsits

userAuthenticateddatamembertotheboolvaluereturnedbythis



functionuserAuthenticatedbecomestrueifauthenticationsucceeds

(i.e.,accountNumberandpinmatchthoseofanexistingAccountin

bankDatabase)andremainsfalseotherwise.IfuserAuthenticatedis

true,line55savestheaccountnumberenteredbytheuser

(i.e.,accountNumber)intheATMdatamembercurrentAccountNumber.

TheothermemberfunctionsofclassATMusethisvariable

wheneveranATMsessionrequiresaccesstotheuser'saccount

number.IfuserAuthenticatedisfalse,lines5859usethescreen's

displayMessageLinememberfunctiontoindicatethataninvalid

accountnumberand/orPINwasenteredandtheusermusttry

again.NotethatwesetcurrentAccountNumberonlyafter

authenticatingtheuser'saccountnumberandtheassociated

PINifthedatabasecouldnotauthenticatetheuser,

currentAccountNumberremains0.

Aftermemberfunctionrunattemptstoauthenticatetheuser

(line30),ifuserAuthenticatedisstillfalse,thewhileloopinlines

2731executesagain.IfuserAuthenticatedisnowTRue,theloop

terminatesandcontrolcontinueswithline33,whichcallsclass

ATM'sutilityfunctionperformTransactions.

MemberfunctionperformTransactions(lines63103)carriesoutan

ATMsessionforanauthenticateduser.Line66declaresalocal

TRansactionpointer,whichweaimataBalanceInquiry,Withdrawalor

DepositobjectrepresentingtheATMtransactioncurrentlybeing

processed.NotethatweuseaTRansactionpointerheretoallow

ustotakeadvantageofpolymorphism.Alsonotethatweuse

therolenameincludedintheclassdiagramofFig.

3.20currentTransactioninnamingthispointer.Asperourpointernamingconvention,weappend"Ptr"totherolenametoform

thevariablenamecurrentTransactionPtr.Line68declaresanother

localvariableaboolcalleduserExitedthatkeepstrackofwhether

theuserhaschosentoexit.Thisvariablecontrolsawhileloop

(lines71102)thatallowstheusertoexecuteanunlimited

numberoftransactionsbeforechoosingtoexit.Withinthisloop,



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

Appendix G. ATM Case Study Code

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

×