1 / 132

基于 UML 的面向对象系统分析与设计

基于 UML 的面向对象系统分析与设计. Lecture 10 Design Pattern. Books. Design Patterns : Elements of Reusable Object-Oriented Software (1995) The-Gang-of-Four (GoF) - Gamma, Helm, Johnson , Vlissides Analysis Patterns - Reusable Object Models Martin Fowler The Design Patterns Smalltalk Companion

Télécharger la présentation

基于 UML 的面向对象系统分析与设计

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 基于UML的面向对象系统分析与设计 Lecture 10 Design Pattern

  2. Books • Design Patterns : Elements of Reusable Object-Oriented Software (1995) • The-Gang-of-Four (GoF) - Gamma, Helm, Johnson , Vlissides • Analysis Patterns - Reusable Object Models • Martin Fowler • The Design Patterns Smalltalk Companion • Alpert, Brown & Woolf

  3. Design Patterns “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice”. --- Christopher Alexander, 1977 This was in describing patterns in buildings and towns. In SE, design patterns are in terms of objects and interfaces, not walls and doors. The manner in which a collection of interacting objects collaborate to accomplish a specific task or provide some specific functionality.

  4. Essential Elements of Design Patterns • Name: identifies a pattern • Problem: describes when to apply the pattern in terms of the problem and context • Solution: describes elements that make up the design, their relationships, responsibilities, and collaborations • Consequences: results and trade-offs of applying the pattern

  5. How to Describe Design Patterns more fully This is critical because the information has to be conveyed to peer developers in order for them to be able to evaluate, select and utilize patterns. • A format for design patterns • Pattern Name and Classification • Intent • Also Known As • Motivation • Applicability • Structure • Participants • Collaborations • Consequences • Implementation • Sample Code • Known Uses • Related Patterns

  6. Organizing Design Patterns • By Purpose (reflects what a pattern does): • Creational Patterns • Structural Patterns • Behavioral Patterns • By Scope: specifies whether the pattern applies primarily to • classes or to • objects.

  7. Design Patterns Space Purpose Creational Structural Behavioral Scope Class Factory Method Adapter Interpreter Template Object Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade Flyweight Proxy Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor

  8. Some Design Patterns Pattern Name Role Convert the interface of one class into another interface Adapter clients expect. Adapter allows classes to work together that otherwise can’t because of incompatible interfaces. Provide a surrogate or placeholder for another object. Proxy Define an object that encapsulates how a set of Mediator objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly and let one vary its interaction independently Define a one-to-many dependency between Observer objects so that when one object changes state, all its dependents will be notified and updated automatically. Define the skeleton of an algorithm in an Template operation, deferring some steps to subclasses.

  9. Creational Patterns • Creational Patterns • Abstract Factory, Factory Method, Singleton • Concerned with object creation • Who creates what, when and how

  10. Structural Patterns • Structural Patterns • Concerned with the composition of classes or objects • Structural class patterns use inheritance to compose interfaces or implementations. • Structural object patterns describe ways to compose objects to realize new functionality.

  11. Behavioral Patterns • Behavioral Patterns • Characterize the ways in which classes or objects interact and distribute responsibility • Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. • Behavioral patterns also describe patterns of communication between objects and classes.

  12. Sample - Adapter Pattern Structural Pattern

  13. Adapter • Intermediary acts like a translator between the client and the server. Server Client Adapter

  14. Example • Requirements Change • Add Triangle object

  15. Example • Suppose XTriangle class has already existed • Xdraw • Xgetarea • Solutions: • Create class Triangle derives from Shape • Triangle contains Xtriangle (composition relationship) • Triangle passes requests made to the Triangle object on through to the XTriangle object

  16. Example Class Triangle extends Shape{ … private XTriangle tgl … public Triangle(){ tgl=new XTriangle(); } void public draw(){ tgl.Xdraw(); } }

  17. Adapter Class Diagram XTriangle Canvas Shape Adaptee Client Target +specificOperation() +request() Triangle Xtriangle.Xdraw() Adapter adaptee.specificOperation() +request()

  18. Adapter • Intent: • Match an existing object beyond your control to a particular interface. • Problem: • A system has the right data and behavior but the wrong interface. Typical used when you have to make something a derivative of an abstract class we are defining or already have. • Solution: • The adapter provides a wrapper with the desired interface. • Participants and Collaborators: • The Adapter adapts the interface of an Adaptee to match that of Adapter’s Target(the class it derives from). This allows the Client to use the Adaptee as if it were a type of Target. • Consequences: • The Adapter pattern allows for preexisting objects to fit into new class structures without being limited by their interfaces. • Implementation: • Contain the existing class in another class. Have the containing class match the required interface and call the methods of the contained class.

  19. Adapter Participants • Target— defines the domain-specific interface that the client uses. • Client— collaborates with objects conforming to the Target interface. • Adaptee— defines an existing interface that needs adapting. • Adapter— adapts the interface of Adaptee to the Target interface. Collaborations • Clients call operations on an Adapter instance. In turn, the Adapter calls Adaptee operations that carry out the request.

  20. Adapter Summery • Name: Adapter • Intent: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. • Motivation: Sometimes a toolkit class that's designed for reuse isn't reusable only because its interface doesn't match the domain-specific interface an application requires.

  21. Adapter Summery • Applicability – use the Adapter when: • You want to use an existing class, and its interface does not match the one you need. • You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don’t necessarily have compatible interfaces. • (object adapter only) you need to use several existing subclasses, but it’s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.

  22. Task • Creational Pattern • Singleton • Abstract Factory • Factory Method • Structural Pattern • Bridge • Facade • Decorator • Behavioral Pattern • Strategy • Observer • Template Method • ……..

  23. MORE… FYI

  24. Singleton Pattern CreationalPattern

  25. Singleton Pattern • The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. • Examples: • There can be many printers in a system but there should only be one printer spooler. • There should be only one instance of a WindowManager. • There should be only one instance of a filesystem.

  26. Singleton Pattern • How do we ensure that a class has only one instance and that the instance is easily accessible? • A global variable makes an object accessible, but does not keep you from instantiating multiple objects. • A better solution is to make the class itself responsible for keeping track of its sole instance. The class ensures that no other instance can be created (by intercepting requests to create new objects) and it provides a way to access the instance.

  27. Singleton Pattern Use the Singleton pattern when • There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. • When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

  28. Singleton Class Diagram

  29. Singleton Particpants • Singleton • Defines an Instance operation that lets clients access its unique instance. Instance is a class operation (static method) • Responsible for creating its own unique instance • Client • Accesses a Singleton instance solely through the Singleton’s Instance() method.

  30. Singleton Consequences • Controlled access to sole instance Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it. • Reduced name space The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.

  31. Singleton Consequences • Permits refinement of operations and representations The Singleton class may be subclassed and it is easy to configure an application with an instance of this extended class at run-time. • More flexible than class operations An alternative is to use static member functions. However it is difficult to change the design to allow more than one instance of a class and static member functions are not polymorphic, so subclasses can not override them.

  32. Singleton Implementation • Ensuring a unique instance The Singleton pattern makes the sole instance a normal instance of a class, but that class is written so that only one instance can ever be created. A common way to do this is to hide the operation that creates the instance behind a static class operation that guarantees that only one instance is created.

  33. Singleton Sample Code class Singleton { private static Singleton instance; static Singleton getInstance() { if (instance == null) // if not created yet instance = new Singleton(); // create once return instance; } // clients access the Singleton exclusively through // the getInstance() member function protected Singleton() {} // the constructor is protected, such that a client // can never instantiate a Singleton } lazy instantiation

  34. Singleton Sample Code class Singleton { private static Singleton instance; static Singleton Instance(SingletonType t) { if (instance == null) { if (t==SINGLETON) instance = new Singleton(); if (t==MYSINGLETON) instance = new MySingleton(); } return instance; } protected Singleton() {} } class MySingleton extends Singleton { … }

  35. Problems with the above implementation • protected constructors can be called by subclasses and by other classes in the same package • two solutions: • make the ClassicSingleton constructor private so that only ClassicSingleton() methods call it; however, that means ClassicSingleton cannot be subclassed • put singleton class in an explicit package, so classes in other packages (including the default package) cannot instantiate singleton instances

  36. Factory Method Pattern

  37. Factory Method • Factory Method defines an interface for creating an object, but let subclasses decide which class to instantiate. • Factory Method lets a class defer instantiation to subclasses.

  38. Factory Method • Frameworks use abstract classes to define and maintain relationships between objects. • A Framework is often responsible for creating these objects as well. • Consider a framework for applications that can present multiple documents to the user. • The framework contains abstractions for Application and Document. • Both classes are abstract and clients have to subclass them to realize their application-specific implementations. • To create a drawing application for example, we define sub-classes DrawingApplication and DrawingDocument.

  39. Factory Method • The particular Document sub-class is application specific, the Application class can not predict the sub-class of a Document to instantiate. • The Application only knows when a new document should be created, not what kind of Document to create. • The problem, the framework must instantiate classes, but it only knows about abstract classes, which it cannot instantiate. • The Factory Method encapsulates the knowledge of which Document sub-class to create and moves this knowledge out of the framework.

  40. Factory Method Class Diagram

  41. Factory Method Applicability Use the Factory Method pattern when • A class cannot anticipate the class of objects it must create. • A class wants its sub-classes to specify the objects it creates. • Classes delegate responsibility to one of several helper sub-classes, and you want to localize the knowledge of which helper sub-class is the delegate.

  42. Factory Method Class Diagram

  43. Factory Method Participants • Product • Defines the interface of objects the factory method creates • ConcreteProduct • Implements the Product interface

  44. Factory Method Participants • Creator • Declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct • May call the factory method to create a Product object • ConcreteCreator • Overrides the factory method to return an instance of a ConcreteProduct

  45. Factory Method Consequences • Factory eliminates the need to bind application-specific classes into your code. The code only deals with the Product interface, therefore it can work with any user-defined Concrete-Product classes. • A potential disadvantage is that clients might have to sub-class the Creator class just to create a particular ConcreteProduct object.

  46. Factory Method Consequences • Provides hooks for subclasses: Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory methods give sub-classes a hook for providing an extended version of an object. • Connects parallel class hierarchies:

  47. Factory Method Implementation • Two main variations of Factory Method • Creator is an abstract class and does not provide an implementation for factory method. Requires sub-classes to define an implementation, but you do not have to instantiate unforeseeable classes. • Creator is a concrete class and provides a default implementation for factory method. The Creator uses the factory method primarily for flexibility, allowing sub-classes to change the class of objects their parent class instantiates if necessary.

  48. Factory Method Implementation • Parameterized factory methods • The factory method can create multiple kinds of products. The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates share the Product interface. class Creator { Product FactoryMethod(ProductID id) { if (id==MINE) return new MyProduct(); if(id==YOURS) return new YourProduct(); } }

  49. Factory Method Implementation • Using templates to avoid subclassing: In C++ one can use a template sub-class of Creator that is parameterized by the Product class. template <class TheProduct > class Creator { public: virtual Product* CreateProduct() { return new TheProduct; }; }; Class MyProduct : public Product { … }; Creator<MyProduct> my Creator;

  50. Abstract Factory Pattern

More Related