軟件系統(tǒng)設(shè)計與體系結(jié)構(gòu):Ch12 Design Patterns(4)_第1頁
軟件系統(tǒng)設(shè)計與體系結(jié)構(gòu):Ch12 Design Patterns(4)_第2頁
軟件系統(tǒng)設(shè)計與體系結(jié)構(gòu):Ch12 Design Patterns(4)_第3頁
軟件系統(tǒng)設(shè)計與體系結(jié)構(gòu):Ch12 Design Patterns(4)_第4頁
軟件系統(tǒng)設(shè)計與體系結(jié)構(gòu):Ch12 Design Patterns(4)_第5頁
已閱讀5頁,還剩55頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、 Ch12 Design Patterns(4)Data Types (Recursive) Data TypesCreationSoftware System Design and ArchitectureMain ContentsData Types (Recursive) Data TypesCreationComposite: IntentCompose objects into tree structures to represent part-whole hierarchies.Composite lets clients treat individual objects and

2、compositions of objects in a uniform way.Composite: Motivation Dynamic StructureComposite: Motivation Static StructureComposite: Structure (for transparency)Structure (for safety)The Decorator Pattern: The SolutionInterpreterIntentGiven a language, define a representation for its grammar along with

3、an interpreter that uses the representation to interpret sentences in the languageMotivationInterpreting and evaluating expressions governed by a rules of some language is a common programming probleme.g., arithmetic expressions, regular expressionsThis pattern provides a way to define the grammar f

4、or the language, represent sentences, and then interpret those sentencesDesign SolutionParticipants Client, context, expressionClient typically calls an evaluate method on the context objectThe call, in turn, calls interpret on several expression objects, and culminates in a returned resultThe expre

5、ssion objects together represent the entire sentence, and hence are usually contained in another objectMain ContentsData Types (Recursive) Data TypesCreationNull object: Uncertainty Delegatorintent: The null object pattern provides an alternative to using null to indicate the absence of an object.no

6、t forced to test for null before using itcan implement default behaviore.g.we want to provide a facility which is able to route warnings/error messages to different locationsdialog boxa log filenowhere at allSource Classboolean isNull()return falseNull ClassisNull()return TrueisNull()Is inheritedNor

7、mal classNull object - StructureDelegatorOperationIFNullOperationRealOperation11uses The Immutable PatternContext: An immutable object is an object that has a state that never changes after creation Problem: How do you create a class whose instances are immutable? Forces: There must be no loopholes

8、that would allow illegal modification of an immutable object Solution: Ensure that the constructor of the immutable class is the only place where the values of instance variables are set or modified. Instance methods which access properties must not have side effects. If a method that would otherwis

9、e modify an instance variable is required, then it has to return a new instance of the class. The Read-only Interface PatternContext: You sometimes want certain privileged classes to be able to modify attributes of objects that are otherwise immutable Problem: How do you create a situation where som

10、e classes see a class as read-only whereas others are able to make modifications?Read-only InterfaceSolution:UnprivilegedClass*MutatorMutableattribute privategetAttributesetAttributeinterfaceReadOnlyInterfacegetAttribute*EntitiesAn entity is an object that represents a persistent business entity suc

11、h as an account or a customer.Entities must persist between the sessions or transactions that use them.Entities are stored in files or databasesEntities are beansSimple or EJB.Example: A Person Entitypublic class Person extends Entity private String first; private String last; private Address addres

12、s; private Phone phone; public Phone getPhone() return phone; public void setPhone(Phone p) phone = p; / etc.Value ObjectsA value object holds the attributes of one or more entities in public fields.Pass value objects, not entities, between layers.Implementation of Serializable should be consideredV

13、alue objects can update and create entities.Entities can create value objects.public class PersonVO extends ValueObject public String first; public String last; public int addressOid; public String street; public String apartment; public String city; public String state ; public String zip; public i

14、nt phoneOid; public String phone; public void update(Person per) . public Person makePerson() . Example: Person VOAddress Book EntitiesMain ContentsData Types (Recursive) Data TypesCreationObject creation: SimpleCreational connections with othersUnlimited instancesCreating one typeSimple instantiati

15、on and initializationMethodsCreator patternCoupling patternCohesion patternObject creation: ComplexScenario 1: only one instance permittedPattern: Singletonproblem: sometimes we will really only ever need one instance of a particular classexamples: keyboard reader, bank data collectionwed like to ma

16、ke it illegal to have more than one, just for safetys sakeSingleton: structureSingleton-static uniqueInstance-+static getinstance()-singleton()+return uniqueInstanceImplementing Singletonmake constructor(s) private so that they can not be called from outsidedeclare a single static private instance o

17、f the classwrite a public getInstance() or similar method that allows access to the single instancepossibly protect / synchronize this method to ensure that it will work in a multi-threaded program28Singleton exampleconsider a singleton class RandomGenerator that generates random numberspublic class

18、 RandomGenerator private static RandomGenerator gen; public static RandomGenerator getInstance() if (gen = null) gen = new RandomGenerator(); return gen; private RandomGenerator() public double nextNumber() return Math.random(); Object creation: ComplexScenario 2: Limited instance permitted思考題以singl

19、eton為基礎(chǔ),編寫程序解決上述問題Object creation: ComplexScenario 3: type variationsEncapsulating object creationFactoryFactory: a class which responsibility is to creating other class with vary typesA More complex scenario: type variationsApplicationnewDocument()openDocument()Documentsave()print()docsMyDocumentMy

20、ApplicationcreatesApplication class is responsible for creation (and management) of DocumentsProblem:Application class knows: WHEN a new document should be createdApplication class doesnt know: WHAT KIND of document to createA More complex scenario: type variationsSolution:Application defines a virt

21、ual function, createDocument()MyApplication makes sure that createDocument() will create a product (Document) of the correct type.Document doc = createDocument();docs.add(doc);doc.open();ApplicationcreateDocument()newDocument()openDocument()Documentsave()print()docsMyDocumentMyApplicationcreateDocum

22、ent()createsreturn new MyDocument()Factory Method: intentDefine an interface for creating an object, but let subclasses decide which class to instantiate.Lets a class defer instantiation to subclasses.Factory method is not a simple factory!Factory Method: structureProductConcreteProductCreatorfactor

23、yMethod()AnOperation()ConcreteCreatorfactoryMethod()duct= factoryMethod().return new ConcreteProductFactory Method: ConsequencesChangeability , ReusabilityConcrete (Dynamic) types are isolated from the client codeProvides hooks for subclasses: the factory method gives subclasses a hook fo

24、r providing an extended version of an objectConnects parallel class hierarchies: a clients can use factory methods to create a parallel class hierarchyComplexClients might have to subclass the Creator class just to create a particular ConcreteProduct objectTemplate Method PatternDefine the skeleton

25、of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure.39.operation1();.operation2();.operationN();.Factory Method思考題如果有多個其他類實例的創(chuàng)建類型都需要子類來決定怎么辦?如果多個其他類實例之間存在類型依賴該怎么辦?Abstrac

26、t Factory: ProblemsIntentProvide an interface for creating families of related or dependent objects without specifying their concrete classesAbstract Factory: The SolutionsAbstractFactoryDeclares an interface for operations that create abstract productsConcreteFactory Implements the operations to cr

27、eate concrete product objects: usuallyinstantiated as a SingletonAbstractProductDeclares an interface for a type of product object; Concrete Factories produce the concrete productsConcreteProduct Defines a product object to be created by the corresponding concrete factoryAbstract Factory: Consequenc

28、esGood:Isolates concrete classesAll manipulation on client-side done through abstract interfacesMakes exchanging product families easyJust change the ConcreteFactoryEnforces consistency among productsBadSupporting new kinds of products is difficultHave to reprogram Abstract Factory and all subclasse

29、sBut its not so bad in dynamically typed languages Object creation: ComplexScenario 3: complex instantiation and initialization, such asRuntime instantiationValue varies in initializationPattern: Prototypeproblem: Specify the kinds of objects to create using a prototypical instance, and create new o

30、bjects by copying this prototypePrototype: structurep = prototype-clone()Prototypeclone()prototypeClientoperation()ConcretePrototype1clone()ConcretePrototypeclone()return copy of selfreturn copy of selfPrototype pattern - consequencesAdding and removing prototypes at run-timeSpecifying new objects by varyin

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論