资源预览内容
第1页 / 共60页
第2页 / 共60页
第3页 / 共60页
第4页 / 共60页
第5页 / 共60页
第6页 / 共60页
第7页 / 共60页
第8页 / 共60页
第9页 / 共60页
第10页 / 共60页
亲,该文档总共60页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
Ch12 Design Patterns(4)Data Types (Recursive) Data TypesCreationSoftware System Design and ArchitectureMain ContentsnData Types (Recursive) nData TypesnCreationComposite: IntentnCompose objects into tree structures to represent part-whole hierarchies.nComposite lets clients treat individual objects and compositions of objects in a uniform way.Composite: Motivation Dynamic StructureComposite: Motivation Static StructureComposite: Structure (for transparency)Structure (for safety)The Decorator Pattern: The SolutionInterpreternIntentqGiven a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the languagenMotivationqInterpreting and evaluating expressions governed by a rules of some language is a common programming problemne.g., arithmetic expressions, regular expressionsqThis pattern provides a way to define the grammar for the language, represent sentences, and then interpret those sentencesDesign SolutionParticipants nClient, context, expressionnClient typically calls an evaluate method on the context objectnThe call, in turn, calls interpret on several expression objects, and culminates in a returned resultqThe expression objects together represent the entire sentence, and hence are usually contained in another objectMain ContentsnData Types (Recursive) nData TypesnCreationNull object: Uncertainty Delegatornintent: The null object pattern provides an alternative to using null to indicate the absence of an object.nnot forced to test for null before using itqcan implement default behaviorne.g.qwe want to provide a facility which is able to route warnings/error messages to different locationsndialog boxna log filennowhere at allnSource Classboolean isNull()return falseNull ClassisNull()return TrueisNull()Is inheritedNormal classNull object - StructureDelegatorOperationIFNullOperationRealOperation11uses The Immutable PatternqContext: nAn immutable object is an object that has a state that never changes after creation qProblem: nHow do you create a class whose instances are immutable? qForces: nThere must be no loopholes that would allow illegal modification of an immutable object qSolution: nEnsure that the constructor of the immutable class is the only place where the values of instance variables are set or modified. nInstance methods which access properties must not have side effects. nIf a method that would otherwise modify an instance variable is required, then it has to return a new instance of the class. The Read-only Interface PatternqContext: nYou sometimes want certain privileged classes to be able to modify attributes of objects that are otherwise immutable qProblem: nHow do you create a situation where some classes see a class as read-only whereas others are able to make modifications?Read-only InterfaceqSolution:UnprivilegedClass* * * * * *MutatorMutableattribute privategetAttributesetAttributeinterfaceReadOnlyInterfacegetAttribute* * * * *EntitiesnAn entity is an object that represents a persistent business entity such as an account or a customer.nEntities must persist between the sessions or transactions that use them.nEntities are stored in files or databasesnEntities are beansqSimple or EJB.Example: A Person Entitypublic class Person extends Entity private String first; private String last; private Address address; private Phone phone; public Phone getPhone() return phone; public void setPhone(Phone p) phone = p; / etc.Value ObjectsnA value object holds the attributes of one or more entities in public fields.nPass value objects, not entities, between layers.nImplementation of Serializable should be considerednValue objects can update and create entities.nEntities 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 int phoneOid; public String phone; public void update(Person per) . public Person makePerson() . Example: Person VOAddress Book EntitiesMain ContentsnData Types (Recursive) nData TypesnCreationObject creation: SimplenCreational connections with othersqUnlimited instancesqCreating one typeqSimple instantiation and initializationnMethodsqCreator patternqCoupling patternqCohesion patternObject creation: ComplexnScenario 1: only one instance permittednPattern: Singletonqproblem: sometimes we will really only ever need one instance of a particular classnexamples: keyboard reader, bank data collectionnwed like to make it illegal to have more than one, just for safetys sakeSingleton: structureSingleton-static uniqueInstance-+static getinstance()-singleton()+return uniqueInstanceImplementing Singletonnmake constructor(s) private so that they can not be called from outsidendeclare a single static private instance of the classnwrite a public getInstance() or similar method that allows access to the single instanceqpossibly protect / synchronize this method to ensure that it will work in a multi-threaded program28Singleton examplenconsider a singleton class RandomGenerator that generates random numberspublic class 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: ComplexnScenario 2: Limited instance permittedn思考题q以singleton为基础,编写程序解决上述问题Object creation: ComplexnScenario 3: type variationsEncapsulating object creationFactorynFactory: a class which responsibility is to creating other class with vary typesA More complex scenario: type variationsApplicationnewDocument()openDocument()Documentsave()print()docsMyDocumentMyApplicationcreatesApplication 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 variationsnSolution:qApplication defines a virtual function, createDocument()qMyApplication 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()docsMyDocumentMyApplicationcreateDocument()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: structureProductConcreteProductCreatorfactoryMethod()AnOperation()ConcreteCreatorfactoryMethod()creates.product= factoryMethod().return new ConcreteProductFactory Method: ConsequencesnChangeability , ReusabilityqConcrete (Dynamic) types are isolated from the client codeqProvides hooks for subclasses: the factory method gives subclasses a hook for providing an extended version of an objectqConnects parallel class hierarchies: a clients can use factory methods to create a parallel class hierarchynComplexqClients might have to subclass the Creator class just to create a particular ConcreteProduct objectTemplate Method PatternnDefine the skeleton 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 Methodn思考题q如果有多个其他类实例的创建类型都需要子类来决定怎么办?q如果多个其他类实例之间存在类型依赖该怎么办?Abstract Factory: ProblemsnIntentqProvide an interface for creating families of related or dependent objects without specifying their concrete classesAbstract Factory: The SolutionsnAbstractFactoryDeclares an interface for operations that create abstract productsnConcreteFactory Implements the operations to create concrete product objects: usuallyinstantiated as a SingletonnAbstractProductDeclares an interface for a type of product object; Concrete Factories produce the concrete productsnConcreteProduct Defines a product object to be created by the corresponding concrete factoryAbstract Factory: ConsequencesnGood:qIsolates concrete classesnAll manipulation on client-side done through abstract interfacesqMakes exchanging product families easynJust change the ConcreteFactoryqEnforces consistency among productsnBadqSupporting new kinds of products is difficultqHave to reprogram Abstract Factory and all subclassesqBut its not so bad in dynamically typed languages Object creation: ComplexnScenario 3: complex instantiation and initialization, such asqRuntime instantiationqValue varies in initializationnPattern: Prototypeqproblem: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototypePrototype: structurep = prototype-clone()Prototypeclone()prototypeClientoperation()ConcretePrototype1clone()ConcretePrototypeclone()return copy of selfreturn copy of selfPrototype pattern - consequencesnAdding and removing prototypes at run-timenSpecifying new objects by varying valuesqBy adding a new prototype you actually define a new type which your program can instantiatenPseudo Dynamic loading Design Pattern Summaryn目标:生产性语言n实际q弥补载体的缺陷q提高质量q特定问题n不要误用或者过用设计模式!n要注意设计模式的代码细节!弥补载体的缺陷的设计模式n集合类型的封装不完整n层次结构的缺失n程序调用的强绑定(运行时注册)问题ncreateIterator( )Iterator PatternStructure/client codeAggregate myList = new ConcreteAggregate( );Iterator itr = myList.createIterator( );The Facade Design Pattern: SolutionObserver PatternObserver and Event设计模式与质量nGoF的主要目标是可维护性:可变更、OCPn可维护性与可理解性可能会冲突q不要误用或者过用设计模式!Pattern: Strategynobjects that hold alternate algorithms to solve a problem53The Decorator Pattern: The SolutionThe Bridge Pattern: The Solution设计模式与质量n其他质量也有设计模式nA survey on security patterns nA SURVEY OF SOFTWARE FAULT TOLERANCE TECHNIQUES nImproving software usability through architectural patterns nTOWARDS A TAXONOMY OF ARCHITECTURE INTEGRATION STRATEGIES Secure LoggerFeedback patternData column pattern设计模式与特定问题n对象创建问题q代码的重复:Factoryq构造方法不能多态:Factory MethodnJ2EE与.NET技术主题nDB技术主题n分布式系统n更多特定问题:设计模式语言(卷15)
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号