Design Patterns 设计模式.docx
《Design Patterns 设计模式.docx》由会员分享,可在线阅读,更多相关《Design Patterns 设计模式.docx(37页珍藏版)》请在冰豆网上搜索。
DesignPatterns设计模式
2012/11/19Monday
设计模式分类标准
1设计模式有两种分类标准,按用途来分:
2按scope来分,主要分成类模式和对象模式两类。
a)类模式处理类和其子类之间的关系,这种关系一般是通过继承实现的,因此在编译时就已经确定。
b)对象模式处理对象间的关系,这种关系可在运行时修改,更灵活。
c)因为大部分的模式都用到了继承,因此只有少数几个模式被认为是类模式。
Classpatternsdealwithrelationshipsbetweenclassesandtheirsubclasses.Theserelationshipsareestablishedthroughinheritance,sotheyarestatic—fixedatcompile-time.Objectpatternsdealwithobjectrelationships,whichcanbechangedatrun-timeandaremoredynamic.Almostallpatternsuseinheritancetosomeextent.Sotheonlypatternslabeled"classpatterns"arethosethatfocusonclassrelationships.NotethatmostpatternsareintheObjectscope.
3Anobjectpackagesbothdataandtheproceduresthatoperateonthatdata.Theproceduresaretypicallycalledmethodsoroperations.Anobjectperformsanoperationwhenitreceivesarequest(ormessage)fromaclient.
4Requestsaretheonlywaytogetanobjecttoexecuteanoperation.Operationsaretheonlywaytochangeanobject'sinternaldata.Becauseoftheserestrictions,theobject'sinternalstateissaidtobeencapsulated;itcannotbeaccesseddirectly,anditsrepresentationisinvisiblefromoutsidetheobject.
5面向对象设计的难点:
decomposingasystemintoobjects,可考虑的因素太多,又没有唯一合适的标准。
6Manyobjectsinadesigncomefromtheanalysismodel.Butobject-orienteddesignsoftenendupwithclassesthathavenocounterpartsintherealworld.Someofthesearelow-levelclasseslikearrays.Othersaremuchhigher-level.Forexample,theComposite(183)patternintroducesanabstractionfortreatingobjectsuniformlythatdoesn'thaveaphysicalcounterpart.Strictmodelingoftherealworldleadstoasystemthatreflectstoday'srealitiesbutnotnecessarilytomorrow's.Theabstractionsthatemergeduringdesignarekeytomakingadesignflexible.
7Everyoperationdeclaredbyanobjectspecifiestheoperation'sname,theobjectsittakesasparameters,andtheoperation'sreturnvalue.Thisisknownastheoperation'ssignature.Thesetofallsignaturesdefinedbyanobject'soperationsiscalledtheinterfacetotheobject.
8Atypeisanameusedtodenoteaparticularinterface.
9Therun-timeassociationofarequesttoanobjectandoneofitsoperationsisknownasdynamicbinding.
10,dynamicbindingletsyousubstituteobjectsthathaveidenticalinterfacesforeachotheratrun-time.Thissubstitutabilityisknownaspolymorphism,andit'sakeyconceptinobject-orientedsystems.
11Anobject'simplementationisdefinedbyitsclass.Theclassspecifiestheobject'sinternaldataandrepresentationanddefinestheoperationstheobjectcanperform.
12Objectsarecreatedbyinstantiatingaclass.Theobjectissaidtobeaninstanceoftheclass.Theprocessofinstantiatingaclassallocatesstoragefortheobject'sinternaldata(madeupofinstancevariables)andassociatestheoperationswiththesedata.
13Adashedarrowheadlineindicatesaclassthatinstantiatesobjectsofanotherclass.Thearrowpointstotheclassoftheinstantiatedobjects.
14接口继承与类继承差别特别大。
sdefineshowtheobjectisimplemented.Theclassdefinestheobject'sinternalstateandtheimplementationofitsoperations.Incontrast,anobject'stypeonlyreferstoitsinterface—thesetofrequeststowhichitcanrespond.Anobjectcanhavemanytypes,andobjectsofdifferentclassescanhavethesametype.
15Becauseaclassdefinestheoperationsanobjectcanperform,italsodefinestheobject'stype.
16Classinheritance是一种mechanismforcodeandrepresentationsharing.interfaceinheritance(orsubtyping)describeswhenanobjectcanbeusedinplaceofanother.
17Programtoaninterface,notanimplementation.
18Don'tdeclarevariablestobeinstancesofparticularconcreteclasses.Instead,commitonlytoaninterfacedefinedbyanabstractclass.Youwillfindthistobeacommonthemeofthedesignpatternsinthisbook.
19面向对象设计中复用的两种基本方法:
classinheritance、objectcomposition.
20white-boxreuse:
Reusebysubclassing。
theinternalsofparentclassesareoftenvisibletosubclasses.
21Objectcompositionrequiresthattheobjectsbeingcomposedhavewell-definedinterfaces.Thisstyleofreuseiscalledblack-boxreuse,becausenointernaldetailsofobjectsarevisible.
22inheritanceexposesasubclasstodetailsofitsparent'simplementation,"inheritancebreaksencapsulation"
23Onecureforthisistoinheritonlyfromabstractclasses,sincetheyusuallyprovidelittleornoimplementation.
24Objectcompositionisdefineddynamicallyatrun-timethroughobjectsacquiringreferencestootherobjects.
25使用objectcompositionhelpsyoukeepeachclassencapsulatedandfocusedononetask。
Yourclassesandclasshierarchieswillremainsmallandwillbelesslikelytogrowintounmanageablemonsters.
26另外,,adesignbasedonobjectcompositionwillhavemoreobjects(iffewerclasses),andthesystem'sbehaviorwilldependontheirinterrelationshipsinsteadofbeingdefinedinoneclass.
27Favorobjectcompositionoverclassinheritance.
28继承和组合合作的方式:
Ideally,youshouldn'thavetocreatenewcomponentstoachievereuse.Youshouldbeabletogetallthefunctionalityyouneedjustbyassemblingexistingcomponentsthroughobjectcomposition.Butthisisrarelythecase,becausethesetofavailablecomponentsisneverquiterichenoughinpractice.Reusebyinheritancemakesiteasiertomakenewcomponentsthatcanbecomposedwitholdones.Inheritanceandobjectcompositionthusworktogether.
29Delegation使得composition像inheritance一样拥有强大的复用功能。
30代理的基本原理areceivingobjectdelegatesoperationstoitsdelegate.Thisisanalogoustosubclassesdeferringrequeststoparentclasses.Butwithinheritance,aninheritedoperationcanalwaysrefertothereceivingobjectthroughthethismembervariableinC++andselfinSmalltalk.Toachievethesameeffectwithdelegation,thereceiverpassesitselftothedelegatetoletthedelegatedoperationrefertothereceiver.
31ThefollowingdiagramdepictstheWindowclassdelegatingitsAreaoperationtoaRectangleinstance.
Aplainarrowheadlineindicatesthataclasskeepsareferencetoaninstanceofanotherclass.Thereferencehasanoptionalname,"rectangle"inthiscase.
32Themainadvantageofdelegationisthatitmakesiteasytocomposebehaviorsatrun-timeandtochangethewaythey'recomposed.Ourwindowcanbecomecircularatrun-timesimplybyreplacingitsRectangleinstancewithaCircleinstance,assumingRectangleandCirclehavethesametype.
33Delegation的缺点,与composition在带来灵活性的同时有其固有的缺点一样:
比起morestaticsoftware,它们更难理解。
34Delegationisagooddesignchoiceonlywhenitsimplifiesmorethanitcomplicates.Delegationworksbestwhenit'susedinhighlystylizedways—thatis,instandardpatterns.
35Delegationisanextremeexampleofobjectcomposition.Itshowsthatyoucanalwaysreplaceinheritancewithobjectcompositionasamechanismforcodereuse.
36parameterizedtypes、generics、templates。
defineatypewithoutspecifyingalltheothertypesituses。
Theunspecifiedtypesaresuppliedasparametersatthepointofuse.ThelanguageimplementationwillcreateacustomizedversionoftheListclasstemplateforeachtypeofelement.会创建新类型
37Parameterizedtypesgiveusathirdway(inadditiontoclassinheritanceandobjectcomposition)tocomposebehaviorinobject-orientedsystems.Manydesignscanbeimplementedusinganyofthesethreetechniques.
2012/11/20Tue
1三种复用方式的比较:
Thereareimportantdifferencesbetweenthesetechniques.Objectcompositionletsyouchangethebehaviorbeingcomposedatrun-time,butitalsorequiresindirectionandcanbelessefficient.Inheritanceletsyouprovidedefaultimplementationsforoperationsandletssubclassesoverridethem.Parameterizedtypesletyouchangethetypesthataclasscanuse.Butneitherinheritancenorparameterizedtypescanchangeatrun-time.Whichapproachisbestdependsonyourdesignandimplementationconstraints.
2面对对象程序运行时的程序结构与其代码结构通常没什么关系。
3Acquaintance和Aggregation。
Aggregation关系中两个对象的生命周期一般是相同的。
Acquaintance中则对象相互间并不怎么了解,这种关系又称为association或者using
4DesigningforChange
5需要重设计的几种情况:
a)Creatinganobjectbyspecifyingaclassexplicitly.
b)Dependenceonspecificoperations.
c)Dependenceonhardwareandsoftwareplatform.
d)Dependenceonobjectrepresentationsorimplementations.Clientsthatknowhowanobjectisrepresented,stored,located,orimplementedmightneedtobechangedwhentheobjectchanges.
e)Algorithmicdependencies.
f)Tightcoupling.
g)Extendingfunctionalitybysubclassing.
h)Inabilitytoalterclassesconveniently.比如不能改代码
6Atoolkitisasetofrelatedandreusableclassesdesignedtoprovideuseful,general-purposefunctionality.如C++I/Ostreamlibrary
7ApplicationPrograms比如字处理程序的设计主要考虑internalreuse,maintainability,andextension
8设计Toolkit比设计ApplicationPrograms难多了。
因为不同平台下要都能用
9Aframeworkisasetofcooperatingclassesthatmakeupareusabledesignforaspecificclassofsoftware
10Youcustomizeaframeworktoaparticularapplicationbycreatingapplication-specificsubclassesofabstractclassesfromtheframework.Theframeworkdictatesthearchitectureofyourapplication.Frameworksthusemphasizedesignreuseovercodereuse,thoughaframeworkwillusuallyincludeconcretesubclassesyoucanputtoworkimmediately.
11Framework和Toolkit之间的比较:
Reuseonthislevelleadstoaninversionofcontrolbetweentheapplicationandthesoftwareonwhichit'sbased.Whenyouuseatoolkit(oraconventionalsubroutinelibraryforthatmatter),youwritethemainbodyoftheapplicationandcallthecodeyouwanttoreuse.Whenyouuseaframework,youreusethemainbodyandwritethecodeitcalls.You'llhavetowriteoperationswithparticul