1 / 123

Design Patterns

Design Patterns. Overview. The need to manage complexity Place of data structures and algorithms Class diagrams in UML Beyond objects to patterns Example pattern Reference: Gamma et.al . chapter 1 http://hillside.net/patterns http://www.cs.wustl.edu/~schmidt/patterns-info.html.

coby
Télécharger la présentation

Design Patterns

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. Design Patterns

  2. Overview • The need to manage complexity • Place of data structures and algorithms • Class diagrams in UML • Beyond objects to patterns • Example pattern • Reference: Gamma et.al. chapter 1 • http://hillside.net/patterns • http://www.cs.wustl.edu/~schmidt/patterns-info.html CS351 - Software Engineering (AY2004)

  3. Managing software complexity • There is a desperate need to be able to generate complex, reliable software. • increasing functionality • increasing machine capacity • decreasing software quality • Examples of poor software quality? CS351 - Software Engineering (AY2004)

  4. How can you manage complexity? • Software? Filing system? Building a house? • structure? • components? • techniques? • processes? • Let’s concentrate on structure and see how we can manage complexity there. CS351 - Software Engineering (AY2004)

  5. We tend to learn programming bottom-up • Start with simple values and variables • integers, booleans, reals • assignment, conditional statements, loops • Work up to data structures • sets of values in relationship • commonly occurring abstractions • arrays, linear lists, stacks, queues • trees, graphs • Examine interplay between data structures and algorithms • choice of data structure affects efficiency of algorithm CS351 - Software Engineering (AY2004)

  6. Data structures and classes • In object-oriented terms, data structures and associated algorithms are usually described by abstract data types and encapsulated in objects or classes. • e.g. List, Tree, Graph, Trie, etc. • Get the data structures right and everything else will follow • How do you get the data structures right? • How do you get the classes right? • How do you get a broader view of a system? Another level of abstraction? • consider classes as components • What are good ways of combining classes? • combine classes to give design patterns CS351 - Software Engineering (AY2004)

  7. Abstraction given by class diagrams • Can represent classes as nodes in a graph, with edgesgiving the relationships between the classes • Nodes can indicate state, behaviour (, identity) of classes • State = attributes associated such an object (the instance variables). • Behaviour = operations applicable to such an object (the instance methods). • Identity = unique value that differentiates one object from another (usually implicit) • Examples • Bank account • University professor CS351 - Software Engineering (AY2004)

  8. Nodes can indicate more detail • Note: included attributes do not include references to other objects – include these by associations • Types: • e.g. balance: real • e.g. deposit(amount: real): void • Access control: • public:+ balance: real • protected:# balance: real • private:– balance: real CS351 - Software Engineering (AY2004)

  9. Nodes can indicate more detail • Identify class variables and methods by underlining • Annotate special kinds of components with stereotypes • e.g. «constructor» BankAccount() • e.g. «interface» Graph CS351 - Software Engineering (AY2004)

  10. Class relationships • Classes are related to other classes • a GraphBase class may implement a Graph interface • a GraphImp class may use NodeImp and EdgeImp classes • a SavingsAccount class may extend a BankAccount class • These relationships are drawn as arcs in the class diagram CS351 - Software Engineering (AY2004)

  11. Edge annotations • (Central) label indicates significance of association • context determines which way to read the association • e.g. an Edge joins two Nodes • End-point labels indicate roles • implications for implementation • Multiplicity indicates number of participants • e.g. optional: 0..1 • e.g. zero or more: 0..* • e.g. one or more: 1..* Edge Node 1 2 edge node label setLabel(lbl) getLabel() label setLabel(lbl) getLabel() joins CS351 - Software Engineering (AY2004)

  12. Edge annotations • Arrow heads indicate navigation direction • bidirectional navigation • unidirectional navigation • implications for implementation • Style of arrow: • e.g. inherits: A inherits B • e.g. implements: A implements B • e.g.aggregates: A aggregates B • e.g.composite: A is a composite of B CS351 - Software Engineering (AY2004)

  13. Aggregates versus composites • Aggregates and composites indicate a special association • their use is optional • Aggregates indicate a part-whole relationship • Composites indicate a part-whole relationship where thewhole strongly owns the parts • Copy/delete the whole → copy/delete the parts • E.g. student enrolled in a degree – no aggregation • E.g. degree includes compulsory course – aggregation • not composite – courses may belong to multiple degree • E.g. building consists of 4 floors – composite • floors cannot belong to more than one building CS351 - Software Engineering (AY2004)

  14. Specializing BankAccount • Inheritance and software reuse • A bank account with an overdraft facility • A tenured versus contract University teacher • Reuse state and behaviour • Fundamental to the provision of • Graphical User Interfaces. CS351 - Software Engineering (AY2004)

  15. Relating BankAccount and Customer • Objects can use other objects to accomplish their tasks • A bank account could have an associated customer • The customer object could be notified about overdrafts • Reuse state and behaviour • Maintains encapsulation CS351 - Software Engineering (AY2004)

  16. Inheritance versus Composition • Inheritance has been promoted as the reuse mechanism • Experience shows that composition is a cleaner mechanism • Inheritance hierarchies can become overly complex • Inheritance breaks encapsulation (at least partially) • Inheritance is a static compile-time mechanism, whilecomposition can be a dynamic run-time mechanism(added flexibility may be good or bad) • Implementation of parent will affect that of the child CS351 - Software Engineering (AY2004)

  17. Unified Modeling Language (UML) • Previous class diagram notation is part of the UnifiedModelling Language (UML) • arose out of other notations: OMT, Booch, Jacobsen • UML also addresses other models • Use Case diagrams for capturing external interactions • State diagrams for capturing the internal class activity • Interaction diagrams for capturing interaction between classes • Sequence diagrams for capturing more detailedinteraction between classes • Deployment diagrams for relating software to availablehardware • ... CS351 - Software Engineering (AY2004)

  18. Beyond objects • Object-oriented software construction is not enough • Typical systems have a large number of objects/classes • Relationships between classes can be very complex • Becomes unmanageable • Consider commonly occurring sets of classes — patterns • E.g. contract for house sale speaks in terms of Vendors,Purchasers, Premises, Chattels, etc. • A set of objects is required for such a contract CS351 - Software Engineering (AY2004)

  19. Beyond patterns • Patterns may not be enough to structure complex software • You may require a higher level view of the system • This leads to the topic of software architecture ... CS351 - Software Engineering (AY2004)

  20. Example: the Adapter (class) pattern • Consider wanting to use a prebuilt component which doesnot match the interface you assumed • very common when you try to reuse software CS351 - Software Engineering (AY2004)

  21. Example: the Adapter (class) example • Consider supplying a bank account (as above) in terms ofan account which has a single method for changes CS351 - Software Engineering (AY2004)

  22. Example: the Adapter (object) pattern • Consider wanting to use a prebuilt component which doesnot match the interface you assumed • Adaptee is used, not inherited CS351 - Software Engineering (AY2004)

  23. Example: the Adapter (object) pattern • Consider needing a bank account (as above) in terms of anaccount which has a single method for changes. CS351 - Software Engineering (AY2004)

  24. Where next? • Describing and classifying patterns • Creational patterns for more flexible object creation • Reference: Gamma et.al. chapters 3-4 • http://hillside.net/patterns • http://www.cs.wustl.edu/~schmidt/patterns-info.html CS351 - Software Engineering (AY2004)

  25. Reminder • Patterns capture solutions to commonly occurring problems • Many problems arise in the context of GUIs • Authors need to identify 3 distinct uses/contexts beforeclassifying the solution as a pattern • Patterns consist of a number of classes which interact in acertain way (to solve the problem) • Patterns may or may not be applicable in a given context • Many patterns introduce extra levels of indirection • Most problems in Computer Science can be solved withan extra level of indirection CS351 - Software Engineering (AY2004)

  26. Description of patterns • Name — succinct indication of pattern’s purpose • Synopsis — short description of the pattern(for experienced users) • Context — problem description + example problem • Forces — considerations leading to the solution • Solution — describes the general-purpose solution • Consequences — trade-offs and results • Implementation — pitfalls, hints, techniques • Sample code • Related patterns — similar sorts of situations CS351 - Software Engineering (AY2004)

  27. Example description – Adapter pattern • Name: Adapter — Class, Object — Structural • Synopsis: implements an interface known to the clients viaa class which is not known to the clients • Context: the class interfaces derived from the design of asystem may not match the class interface available in areusable library. E.g. BankAccount class with two methodsdeposit(amount) and withdraw(amount) to be adapted to aclass Account which has a single method change(amount)which accepts positive and negative amounts. • Forces: • You want to use an existing class, and its interface doesnot match the one you need • You do not have the option of changing the interface ofthe existing class – maybe the source isn’t available, orthe class is part of a reusable library CS351 - Software Engineering (AY2004)

  28. Example description – Adapter pattern • Solution: A class adapter uses multiple inheritance to adaptone interface to another. An object adapter relies on objectcomposition: • Target defines the domain-specific interface that Clientuses • Client collaborates with objects conforming to theTarget interface • Adaptee defines an existing interface that needsadapting • Adapter adapts the interface of Adaptee to the Targetinterface CS351 - Software Engineering (AY2004)

  29. Example: the Adapter (class) pattern • Reuse a prebuilt class which does not match the interfaceyou assumed • very common when you try to reuse software CS351 - Software Engineering (AY2004)

  30. Java-line code for Adapter class pattern abstract class Target // Maybe an interface { public abstract ResultType request(); … } class Adaptee // An existing class { public ResultType req() { … } … } CS351 - Software Engineering (AY2004)

  31. Java-line code for Adapter class pattern class Adaptor extends Target, Adaptee { public ResultType request() { return req(); // Use Adaptee version } … } • Note that Java does not support multiple inheritance • the above would be possible in C++, Eiffel • the above would be possible if Target were an interface, inwhich case Adaptor would inherit Adaptee and implementTarget CS351 - Software Engineering (AY2004)

  32. The Adapter (object) pattern • Consider wanting to use a prebuilt component which doesnot match the interface you assumed CS351 - Software Engineering (AY2004)

  33. Java-like code for Adapter object pattern • Target and Adaptee classes as before class Adaptor extends Target // Does not inherit Adaptee { Adaptee adpt = new Adaptee(); … public ResultType request() { return adpt.req(); // Use Adaptee version } … } • Note that this works directly in Java CS351 - Software Engineering (AY2004)

  34. Example description: Adapter pattern • Consequences: Class and object adapters have differenttrade-offs. A class adapter • adapts Adaptee to Target by committing to a concreteAdapter class. As a consequence, a class adapterwon’t work when we want to adapt a class and all itssubclasses. • lets Adapter override some of Adaptee’s behaviour,since Adapter is a subclass of Adaptee • introduces only one object, and no additional pointerindirection is needed to get to the Adaptee. CS351 - Software Engineering (AY2004)

  35. Example description: Adapter pattern • Consequences: Class and object adapters have differenttrade-offs. An object adapter • lets a single Adapter work with many Adaptees, i.e. theAdaptee itself and all of its subclasses (if any). TheAdapter can also add functionality to all Adaptees atonce. • makes it harder to override Adaptee behaviour. It willrequire subclassing Adaptee and making Adapter referto the subclass rather than the Adaptee itself. • Related patterns: Facade, Proxy, Strategy CS351 - Software Engineering (AY2004)

  36. Classification of patterns • There are two basic dimensions of classification • Scope: • application primarily to classes or objects? • Purpose: • creational — for creating (and deleting) objects • structural — for composing classes or objects • behavioural — interaction of classes or objects CS351 - Software Engineering (AY2004)

  37. Example classification: Adapter pattern • Adapter is of scope class or object • Adapter is of purpose structural CS351 - Software Engineering (AY2004)

  38. Creational patterns • These patterns provide alternatives to creation of objects byusing the new function which: • fixes the class of object being created • i.e. lacks flexibility / configurability • is independent of other calls to new • i.e. does not relate creation of different kinds of objects • Suppose we have a situation where a number of relatedobjects (or products) need to be created • e.g. set of graphical components with similar look-and-feel • e.g. set of bank accounts with matching audit provisions • A common problem! CS351 - Software Engineering (AY2004)

  39. Abstract factory – object creational • Synopsis: Provides a way to create instances of abstractclasses from a matched set of concrete subclasses • Context: Consider building a GUI framework which shouldwork with multiple windowing systems (e.g. Windows, Motif,MacOS) and should provide consistent look-and-feel. • Forces: Use the Abstract Factory pattern when: • a system should be independent of how its products arecreated, composed and represented • a system should be configured with one of multiplefamilies of products • a family of related products is designed to be usedtogether, and you need to enforce this constraint • you want to provide a class library of products, and onlyreveal their interfaces, not their implementations CS351 - Software Engineering (AY2004)

  40. Abstract factory – object creational • Solution: Define an abstract factory class which hasmethods to generate the different kinds of products. (For awindowing system this could generate matched buttons,scroll bars, fields). The abstract factory is subclassed for aparticular concrete set of products • AbstractFactory – declares an interface for operationsthat create abstract product objects • ConcreteFactory – implements the operations to createconcrete product objects • AbstractProduct – declares an interface for a type ofproduct object • ConcreteProduct – implement the AbstractProductinterface • Client – uses only the interfaces declared byAbstractFactory and AbstractProduct classes CS351 - Software Engineering (AY2004)

  41. Abstract factory – object creational CS351 - Software Engineering (AY2004)

  42. Abstract factory – object creational • Consequences: • It isolates concrete classes • clients are isolated from implementation classes • clients manipulate instances through their abstractinterfaces • It makes exchanging product families easy • It promotes consistency among products • Supporting new kinds of product is difficult • the AbstractFactory interface fixes the set of productsthat can be created • extending the AbstractFactory interface will involvechanging all of the subclasses • The hierarchy of products is independent of the client CS351 - Software Engineering (AY2004)

  43. Lexi: consistent look-and-feel CS351 - Software Engineering (AY2004)

  44. Java code for Abstract Factory pattern abstract class Product1 // Some kind of object { … } abstract class Product2 // Another kind of object { // - related to Product1 … } abstract class AbstractFactory { public abstract Product1 createProduct1(); public abstract Product2 createProduct2(); … } CS351 - Software Engineering (AY2004)

  45. Java code for Abstract Factory pattern class version1Product1 extends Product1 // Specific kind { // of Product1 … } class version1Product2 extends Product2 // Specific kind { // of Product2 … } class version2Product1 extends Product1 // Another kind { // of Product1 … } class version2Product2 extends Product2 // Another kind { // of Product2 … } CS351 - Software Engineering (AY2004)

  46. Java code for Abstract Factory pattern class version1Factory extends AbstractFactory { // Factory for version1 products public Product1 createProduct1() { return new version1Product1(); } public Product2 createProduct2() { return new version1Product1(); } … } • Similarly for a class version2Factory CS351 - Software Engineering (AY2004)

  47. Java code for Abstract Factory pattern class client { static void main() { AbstractFactory fact = new version1Factory(); … ... fact.createProduct1() // version1 products ... fact.createProduct2() } … } • With the one line fact = new version2Factory(), you would end up with version2 products CS351 - Software Engineering (AY2004)

  48. Creational patterns • In the abstract factory the family of related products wasindependent of the client(s) • A GUI framework needs to generate related products, butthe products depend on the structure of the client classes • e.g. a word-processor application needs to generateword-processor documents, and word-processordocuments need to be displayed in word-processorviews • Solution is to define methods in the (generic) client classesto create (generic) objects • then override these methods in a specific application CS351 - Software Engineering (AY2004)

  49. Sample: generic application and documents CS351 - Software Engineering (AY2004)

  50. Factory method – class creational • Synopsis: Define an interface for creating an object, but letsubclasses decide which class to instantiate. FactoryMethod lets a class defer instantiation to subclasses • Context: Example is that of a GUI framework. The genericApplication class will have a method createDocument tocreate a generic document. A specific use of the frameworkfor, say, word-processing GUI would subclass the genericApplication class and override the createDocument methodto generate word-processing documents. • Forces: Use the Factory Method pattern when: • a class can’t anticipate the class of objects it mustcreate • a class wants its subclasses to specify the objects itcreates • the set of classes to be generated may be dynamic CS351 - Software Engineering (AY2004)

More Related