软件系统设计与体系结构:Ch12 Design Patterns(4)

上传人:公**** 文档编号:570013381 上传时间:2024-08-01 格式:PPT 页数:60 大小:1.38MB
返回 下载 相关 举报
软件系统设计与体系结构:Ch12 Design Patterns(4)_第1页
第1页 / 共60页
软件系统设计与体系结构:Ch12 Design Patterns(4)_第2页
第2页 / 共60页
软件系统设计与体系结构:Ch12 Design Patterns(4)_第3页
第3页 / 共60页
软件系统设计与体系结构:Ch12 Design Patterns(4)_第4页
第4页 / 共60页
软件系统设计与体系结构:Ch12 Design Patterns(4)_第5页
第5页 / 共60页
点击查看更多>>
资源描述

《软件系统设计与体系结构:Ch12 Design Patterns(4)》由会员分享,可在线阅读,更多相关《软件系统设计与体系结构:Ch12 Design Patterns(4)(60页珍藏版)》请在金锄头文库上搜索。

1、 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

2、 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 alon

3、g 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 th

4、e 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 r

5、esultqThe 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 abse

6、nce 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

7、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? qFor

8、ces: 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 effe

9、cts. 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:

10、 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

11、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

12、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,

13、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;

14、 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 con

15、nections 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 instanc

16、e 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) privat

17、e 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 e

18、xamplenconsider 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() re

19、turn 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 scen

20、ario: 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

21、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();Applicationcre

22、ateDocument()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.

23、Factory method is not a simple factory!Factory Method: structureProductConcreteProductCreatorfactoryMethod()AnOperation()ConcreteCreatorfactoryMethod()creates.product= factoryMethod().return new ConcreteProductFactory Method: ConsequencesnChangeability , ReusabilityqConcrete (Dynamic) types are isol

24、ated 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 Cr

25、eator 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.operation

26、1();.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 SolutionsnAbstractFactoryD

27、eclares 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 productsnConcr

28、eteProduct 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 consi

29、stency 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

30、 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

31、 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弥

32、补载体的缺陷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 Even

33、t设计模式与质量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)

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 高等教育 > 研究生课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号