资源描述:
《Patterns in C 3, STRATEGY》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、PatternsinC-Part3:STRATEGYByAdamPetersenIdentifyingandexploitingcommonalityisfundamentaltosoftwaredesign.Byencapsulatingandre-usingcommonfunctionality,thequalityofthedesignrisesabovecodeduplicationanddreadedanti-patternslikecopy-paste.Thi
2、spartoftheserieswillinvestigateadesignpatternthataddsflexibilitytocommonsoftwareentitiesbylettingclientscustomizeandextendthemwithoutmodifyingexistingcode.ControlcoupledcustomersToattractandkeepcustomers,manycompaniesoffersomekindofbonussystem.Intheexampleusedint
3、hisarticle,acustomerisplacedineitherofthreecategories:•Bronzecustomers:Get2%reductiononeveryitembought.•Silvercustomers:Get5%reductiononeveryitembought.•Goldcustomers:Get10%offonallitemsandfreeshipping.Asimpleandstraightforwardwaytoimplementapricecalculationbased
4、uponthisbonussystemisthroughconditionallogic.Listing1:Solutionusingconditionallogictypedefenum{bronzeCustomer,silverCustomer,goldCustomer}CustomerCategory;doublecalculatePrice(CustomerCategorycategory,doubletotalAmount,doubleshipping){doubleprice=0;/*Calculatethe
5、totalpricedependingoncustomercategory.*/switch(category){casebronzeCustomer:price=totalAmount*0.98+shipping;break;casesilverCustomer:price=totalAmount*0.95+shipping;break;casegoldCustomer:/*Freeshippingforgoldcustomers.*/price=totalAmount*0.90;break;default:onErr
6、or(“Unsupportedcategory”);break;}returnprice;}Beforefurtherinspectionofthedesign,Iwouldliketopointoutthatrepresentingcurrencyasdoublemayleadtomarginallyinaccurateresults.Carelesslyhandled,theymayturnouttobefatalto,forexample,abankingsystem.Further,securityissuesl
7、ikeapossibleoverflowshouldneverbeignoredinbusinesscode.However,suchissueshavebeendeliberatelyleftoutoftheexampleinordernottolosethefocusontheprobleminthescopeofthisarticle.Returningtothecode,eveninthissimplifiedexample,itispossibletoidentifythreeseriousdesignprob
8、lemswiththeapproach,thatwouldn’tstandupwellinthereal-world:1.Conditionallogic.Thesolutionabovebasicallyswitchesonatypecode,leadingtotheriskofintroducingamainte