版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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为基础,编写程序解决上述问题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思考题如果有多个其他类实例的创建类型都需要子类来决定怎么办?如果多个其他类实例之间存在类型依赖该怎么办?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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 殖业节粮行动实施方案
- 智慧灯杆电导率监测施工方案及技术措施
- 2025-2026学年嘉兴市七年级语文下学期期末试卷附答案解析
- 变电企业主要负责人定期维护安全操作规程
- 2025广东深圳市龙岗区国资国企“稳就业”高校毕业生招聘10人(一)笔试历年参考题库附带答案详解
- 2025年龙港市国有企业面向社会公开招聘产业基金工作人员笔试历年参考题库附带答案详解
- 2025年青岛市政空间开发集团有限责任公司招聘笔试历年参考题库附带答案详解
- 2025年修水县投资集团有限公司及所属企业招聘18人笔试历年参考题库附带答案详解
- 2025山西吕梁孝义市市属国有企业公开招聘工作人员(第二批)笔试历年参考题库附带答案详解
- 2025安徽黄山市徽城投资集团有限公司招聘10人笔试历年参考题库附带答案详解
- 2025年中国移动通信集团新疆有限公司巴州分公司社会招聘笔试参考题库附带答案详解
- 2026年纪检监察室主任选拔面试题
- DBJ33-T 1106-2025 建筑光伏系统应用技术规程
- 桥梁人行道钢格栅铺设施工方案
- DB13∕T 6058-2025 深浅层地下水划分规范
- 投资项目财务测算课件
- 小型工厂安全生产管理制度
- 婴幼儿肥胖管理专家共识解读
- 一分钟客户成交技巧与话术训练
- 河南天一大联考2025-2026学年(上)高一上学期9月检测英语试卷
- 质量工程师年工作总结
评论
0/150
提交评论