Design  Patterns  Dr. K. Priyantha Hewagamage Advanced Software Engineering
What is Design Pattern? What are patterns? Is it algorithm? Is it a design? Can we generate code using a design pattern? “ Are all patterns design patterns?” What can you see in the design pattern? University of Colombo School of Computing Advanced Software Engineering
Introduction The recurring aspects of designs are called  design patterns.   A  pattern  is the outline of a reusable solution to a general problem encountered in a particular context  Many of them have been systematically documented for all software developers to use  A good pattern should Be as general as possible Contain a solution that has been proven to effectively solve the problem in the indicated context.  Studying patterns is an effective way to learn from the experience of others  University of Colombo School of Computing Advanced Software Engineering
Pattern origins and history writings of architect Christopher Alexander (coined this use of the term "pattern" ca. 1977-1979)  Kent Beck and Ward Cunningham, Textronix, OOPSLA'87 (used Alexander's "pattern" ideas for Smalltalk GUI design)   Erich Gamma, Ph. D. thesis, 1988-1991  James Coplien,  Advanced C++ Idioms book , 1989-1991  Gamma, Helm, Johnson, Vlissides  ("Gang of Four“ - GoF) Design Patterns: Elements of Reusable Object-Oriented Software , 1991-1994  PLoPD Conferences and books, 1994-present Buschmann, Meunier, Rohnert, Sommerland, Stal,  Pattern -Oriented Software Architecture: A System of Patterns   (“POSA book”)   University of Colombo School of Computing Advanced Software Engineering
Definitions …  a fully realized form, original, or model accepted or proposed for imitation …[dictionary] ... 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  [Alexander] …  the abstraction from a concrete form which keeps recurring in specific non-arbitrary contexts  [Riehle] University of Colombo School of Computing Advanced Software Engineering
Definitions ….. … both a thing and the instructions for making the thing  [Coplien] ...a literary format for capturing the wisdom and experience of expert designers, and communicating it to novices [ Beck ] University of Colombo School of Computing Advanced Software Engineering
Properties Patterns do... provide common vocabulary  provide “shorthand” for effectively communicating  complex principles help document software architecture capture essential parts of a design in compact form show more than one solution  describe software abstractions University of Colombo School of Computing Advanced Software Engineering
Properties (2) Patterns do not... provide an exact solution solve all design problems only apply for object-oriented design University of Colombo School of Computing Advanced Software Engineering
Ingredients  Example – Context: placing windows in a house forces he wants to sit down and be comfortable he is drawn toward the light solution in every room, make at least one window considering light direction University of Colombo School of Computing Advanced Software Engineering
Pattern description (Pattern template) Context :  The general situation in which the pattern applies  Problem :  A short sentence or two raising the main difficulty. Forces :  The issues or concerns to consider when solving the problem Solution :  The recommended way to solve the problem in the given context.  ‘ to balance the forces’ Antipatterns : (Optional) Solutions that are inferior or do not work in this context.  Related patterns : (Optional)  Patterns that are similar to this pattern.  References : Who developed or inspired the pattern.  University of Colombo School of Computing Advanced Software Engineering
Types of software patterns design patterns   (software design)  [Buschmann-POSA] architectural  (systems design)   design  (micro-architectures) [Gamma-GoF] idioms  (low level)  analysis patterns   (recurring & reusable analysis models)   [Flower] organization patterns   (structure of organizations/projects)   process patterns   (software process design)  domain-specific   patterns University of Colombo School of Computing Advanced Software Engineering
Pattern language [Coplien] … is a structured collection of patterns that build on each other to transform needs and constraints into an architecture  [Software Design Patterns: Common Questions and Answers] … defines collection of patterns and rules to combine them into an architectural style…describe software frameworks or families of related systems  [Patterns Home Page ->Patterns Definitions] University of Colombo School of Computing Advanced Software Engineering
Pattern catalogs and systems pattern catalog  … a collection of related patterns, where patterns are subdivided into small number of broad categories… pattern system … a cohesive set of related patterns, which work together to support the construction and evolution of hole architectures... University of Colombo School of Computing Advanced Software Engineering
Types of Design Patterns Creational Patterns to create objects of the right class for a problem, generally when instances of several different classes are available. Structural Patterns to  form larger structures from individual parts, generally of different classes.  Behavioral Patterns to describe interactions between objects. They focus on how objects communicate with each other.  University of Colombo School of Computing Advanced Software Engineering
Pattern Scope Patterns can be further divided into two categories Object Patterns specify relationships between objects. In general, the purpose of an object pattern is to allow the  instances  of different classes to be used in the same place in a pattern at runtime.   Class Patterns specify the relationship between classes and their subclasses at compile time.  University of Colombo School of Computing Advanced Software Engineering
Design pattern catalog  University of Colombo School of Computing Advanced Software Engineering
The Singleton Pattern It is an object creational pattern. The intent of the Singleton pattern is twofold:  Guarantee that a class has only one instance  Provide access to that instance  University of Colombo School of Computing Advanced Software Engineering
The Singleton Pattern Context :  It is very common to find classes for which only one instance should exist ( singleton)   Problem :  How do you ensure that it is never possible to create more than one instance of a singleton class?  Forces :  The use of a public constructor cannot guarantee that no more than one instance will be created.  The singleton instance must also be accessible to all classes that require it  University of Colombo School of Computing Advanced Software Engineering
Singleton Solution: University of Colombo School of Computing Advanced Software Engineering public class Singleton {  static Singleton theInstance  = new Singleton();  private Singleton() { }  public static Singleton getInstance()  {  return theInstance;  }  } « Singleton » theInstance getInstance
Exercise Dual pattern  Write a class called Dual that has exactly two instances,  instance1 and instance2.  Provide an access method  that allows clients to retrieve both instances of the class. Do not allow clients directly access to the constructor.  University of Colombo School of Computing Advanced Software Engineering
The Abstraction-Occurrence Pattern Context :  Often in a domain model you find a set of related objects ( occurrences) . The members of such a set share common information but also differ from each other in important ways. Problem :  What is the best way to represent such sets of occurrences in a class diagram?   Forces :  You want to represent the members of each set of occurrences without duplicating the common information University of Colombo School of Computing Advanced Software Engineering
Abstraction-Occurrence  Solution: University of Colombo School of Computing Advanced Software Engineering TVSeries seriesName producer Episode number title storySynopsis * * * * * * «Occurrence» «Abstraction» * * * * * * Title name author LibraryItem barCodeNumber * * * * * * isbn publicationDate libOfCongress
Abstraction-Occurrence  Antipatterns: University of Colombo School of Computing Advanced Software Engineering name author LibraryItem barCodeNumber isbn publicationDate libOfCongress Title name author LibraryItem barCodeNumber isbn publicationDate libOfCongress name author LibraryItem barCodeNumber isbn publicationDate libOfCongress GulliversTravels MobyDick
Abstraction-Occurrence Abstraction-Occurrence Square variant University of Colombo School of Computing Advanced Software Engineering ScheduledTrain number SpecificTrain date * * * * ScheduledLeg SpecificLeg actualDepTime * actualArrTime scheduledDepTime scheduledArrTime Station origin destination * *
The General Hierarchy  Pattern Context :  Objects in a hierarchy can have one or more objects above them (superiors),  and one or more objects below them (subordinates).  Some objects cannot have any subordinates  Problem :  How do you represent a hierarchy of objects, in which some objects cannot have subordinates?  Forces :  You want a flexible way of representing the hierarchy  that prevents certain objects from having subordinates All the objects have many common properties and operations   University of Colombo School of Computing Advanced Software Engineering
General Hierarchy Solution: University of Colombo School of Computing Advanced Software Engineering «subordinate» * «Node» «SuperiorNode» «NonSuperiorNode» 0..1 * supervises Manager Employee Technician Secretary 0..1 * contains Directory FileSystemItem File 0..1
General Hierarchy Antipattern: University of Colombo School of Computing Advanced Software Engineering RockRecording BluesRecording ClassicalRecording JazzRecording MusicVideo VideoRecoding AudioRecording Recording
The Player-Role Pattern Context :  A  role  is a particular set of properties associated with an object in a particular context.  An object may  play  different roles in different contexts.  Problem :  How do you best model players and roles so that a player can change roles or possess multiple roles? University of Colombo School of Computing Advanced Software Engineering
Player-Role Forces :  It is desirable to improve encapsulation by capturing the information associated with each separate role in a class. You want to avoid multiple inheritance.  You cannot allow an instance to change class   Solution : University of Colombo School of Computing Advanced Software Engineering «Player» «Role1» «Role2» «AbstractRole»
Player-Role Example 1: University of Colombo School of Computing Advanced Software Engineering
Player-Role Example 2: University of Colombo School of Computing Advanced Software Engineering
Player-Role Antipatterns: Merge all the properties and behaviours into a single «Player» class and not have «Role» classes at all.  Create roles as subclasses of the «Player» class.  University of Colombo School of Computing Advanced Software Engineering
The Observer Pattern Context :  When an association is created between two classes, the code for the classes becomes inseparable.  If you want to reuse one class, then you also have to reuse the other. Problem :  How do you reduce the interconnection between classes, especially between classes that belong to different modules or subsystems? Forces :  You want to maximize the flexibility of the system to the greatest extent possible  University of Colombo School of Computing Advanced Software Engineering
Observer Solution: University of Colombo School of Computing Advanced Software Engineering WeatherViewer * * * * * * * Observers are  notified when a new  prediction is ready Forecaster Observable «ConcreteObservable» «ConcreteObserver» «Observable» addObserver notifyObservers «interface» «Observer» update * * * * * * * «interface» Observer
University of Colombo School of Computing Advanced Software Engineering
University of Colombo School of Computing Advanced Software Engineering
Observer Antipatterns: Connect an observer directly to an observable so that they both have references to each other.  Make the observers  subclasses  of the observable.  University of Colombo School of Computing Advanced Software Engineering
The Delegation Pattern Context :  You are designing a method in a class You realize that another class has a method which provides the required service  Inheritance is not appropriate  E.g. because the isa rule does not apply  Problem :  How can you most effectively make use of a method that already exists in the other class?  Forces :  You want to minimize development cost by reusing methods  University of Colombo School of Computing Advanced Software Engineering
Delegation Solution: University of Colombo School of Computing Advanced Software Engineering delegate.method();  « Delegate » « Delegator » delegatingMethod()  {  }  delegatingMethod method LinkedList addFirst addLast addAfter removeFirst removeLast delete isEmpty Stack push pop isEmpty push() {  list.addFirst(); }
Delegation University of Colombo School of Computing Advanced Software Engineering Example: two levels of delegation
Delegation Antipatterns Overuse generalization and  inherit  the method that is to be reused  Instead of creating a  single  method in the «Delegator» that does nothing other than call a method in the «Delegate consider having many different methods in the «Delegator» call the delegate’s method  Access non-neighboring classes University of Colombo School of Computing Advanced Software Engineering return specificFlight.regularFlight.flightNumber(); return getRegularFlight().flightNumber();
The Adapter Pattern Context :  You are building an inheritance hierarchy and want to incorporate it into an existing class.  The reused class is also often already part of its own inheritance hierarchy. Problem :  How to obtain the power of polymorphism when reusing a class whose methods have the same function but  not  the same signature as the other methods in the hierarchy? Forces :  You do not have access to multiple inheritance or you do not want to use it. University of Colombo School of Computing Advanced Software Engineering
Adapter Solution: University of Colombo School of Computing Advanced Software Engineering «Adaptee» adaptedMethod «Superclass» polymorphicMethod «Adapter» polymorphicMethod() return  adaptee.adaptedMethod(); {  }
Adapter Example: University of Colombo School of Computing Advanced Software Engineering TimsTorus calcVolume ThreeDShape volume Sphere Torus volume() return  TimsTorus.calcVolume(); {  }
Adapters Other Names Wrappers Examples Java Wrapper classes Integer, Float, Double Related Patterns Façade, Read Only Interface, Proxy University of Colombo School of Computing Advanced Software Engineering
The Façade Pattern Context :  Often, an application contains several complex packages.  A programmer working with such packages has to manipulate many different classes  Problem :  How do you simplify the view that programmers have of a complex package?  Forces :  It is hard for a programmer to understand and use an entire subsystem  If several different application classes call methods of the complex package, then any modifications made to the package will necessitate a complete review of all these classes. University of Colombo School of Computing Advanced Software Engineering
Façade Solution: University of Colombo School of Computing Advanced Software Engineering «PackageClass3» «PackageClass2» «PackageClass1» * * * * * * RegularFlight * * * * * * Reservation Airline findFlight makeBooking deleteBooking «Facade»
The Immutable Pattern Context :  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 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 otherwise modify an instance variable is required, then it has to return a  new  instance of the class.  University of Colombo School of Computing Advanced Software Engineering
The Read-only Interface Pattern Context :  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 some classes see a class as read-only whereas others are able to make modifications? Forces :  Restricting access by using the  public ,  protected  and  private  keywords is not adequately selective.  Making access  public  makes it public for both reading and writing  University of Colombo School of Computing Advanced Software Engineering
Read-only Interface Solution: University of Colombo School of Computing Advanced Software Engineering «UnprivilegedClass» * * * * * * «Mutator» «Mutable» attribute «private» getAttribute setAttribute «interface» «ReadOnlyInterface» getAttribute * * * * *
Read-only Interface Example: University of Colombo School of Computing Advanced Software Engineering Mutableperson firstName lastName setFirstName setLastName getName «interface» Person getName
The Proxy Pattern Context :  Often, it is time-consuming and complicated to create instances of a class ( heavyweight  classes).  There is a time delay and a complex mechanism involved in creating the object in memory  Problem :  How to reduce the need to create instances of a heavyweight class?  Forces :  We want all the objects in a domain model to be available for programs to use when they execute a system’s various responsibilities.  It is also important for many objects to persist from run to run of the same program  University of Colombo School of Computing Advanced Software Engineering
Proxy Solution: University of Colombo School of Computing Advanced Software Engineering «interface» «ClassIF» * * * * * * * «Client» «HeavyWeight» «Proxy»
Proxy Example: University of Colombo School of Computing Advanced Software Engineering «interface» ListIF The list elements will  be loaded into local  memory only when  needed. ListProxy PersistentList «interface» Student PersistentStudent StudentProxy
Difficulties and Risks When Creating Class Diagrams  Patterns are not a panacea :   Whenever you see an indication that a pattern should be applied, you might be tempted to blindly apply the pattern. However this can lead to unwise design decisions  .  Resolution: Always understand in depth the forces that need to be balanced, and when other patterns better balance the forces.  Make sure you justify each design decision carefully. University of Colombo School of Computing Advanced Software Engineering
Difficulties and Risks When Creating Class Diagrams Developing patterns is hard Writing a good pattern takes considerable work.  A poor pattern can be hard to apply correctly Resolution:  Do not write patterns for others to use until you have considerable experience both in software design and in the use of patterns.  Take an in-depth course on patterns. Iteratively refine your patterns, and have them peer reviewed at each iteration.   University of Colombo School of Computing Advanced Software Engineering

Design Patterns

  • 1.
    Design Patterns Dr. K. Priyantha Hewagamage Advanced Software Engineering
  • 2.
    What is DesignPattern? What are patterns? Is it algorithm? Is it a design? Can we generate code using a design pattern? “ Are all patterns design patterns?” What can you see in the design pattern? University of Colombo School of Computing Advanced Software Engineering
  • 3.
    Introduction The recurringaspects of designs are called design patterns. A pattern is the outline of a reusable solution to a general problem encountered in a particular context Many of them have been systematically documented for all software developers to use A good pattern should Be as general as possible Contain a solution that has been proven to effectively solve the problem in the indicated context. Studying patterns is an effective way to learn from the experience of others University of Colombo School of Computing Advanced Software Engineering
  • 4.
    Pattern origins andhistory writings of architect Christopher Alexander (coined this use of the term "pattern" ca. 1977-1979) Kent Beck and Ward Cunningham, Textronix, OOPSLA'87 (used Alexander's "pattern" ideas for Smalltalk GUI design) Erich Gamma, Ph. D. thesis, 1988-1991 James Coplien, Advanced C++ Idioms book , 1989-1991 Gamma, Helm, Johnson, Vlissides ("Gang of Four“ - GoF) Design Patterns: Elements of Reusable Object-Oriented Software , 1991-1994 PLoPD Conferences and books, 1994-present Buschmann, Meunier, Rohnert, Sommerland, Stal, Pattern -Oriented Software Architecture: A System of Patterns (“POSA book”) University of Colombo School of Computing Advanced Software Engineering
  • 5.
    Definitions … a fully realized form, original, or model accepted or proposed for imitation …[dictionary] ... 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 [Alexander] … the abstraction from a concrete form which keeps recurring in specific non-arbitrary contexts [Riehle] University of Colombo School of Computing Advanced Software Engineering
  • 6.
    Definitions ….. …both a thing and the instructions for making the thing [Coplien] ...a literary format for capturing the wisdom and experience of expert designers, and communicating it to novices [ Beck ] University of Colombo School of Computing Advanced Software Engineering
  • 7.
    Properties Patterns do...provide common vocabulary provide “shorthand” for effectively communicating complex principles help document software architecture capture essential parts of a design in compact form show more than one solution describe software abstractions University of Colombo School of Computing Advanced Software Engineering
  • 8.
    Properties (2) Patternsdo not... provide an exact solution solve all design problems only apply for object-oriented design University of Colombo School of Computing Advanced Software Engineering
  • 9.
    Ingredients Example– Context: placing windows in a house forces he wants to sit down and be comfortable he is drawn toward the light solution in every room, make at least one window considering light direction University of Colombo School of Computing Advanced Software Engineering
  • 10.
    Pattern description (Patterntemplate) Context : The general situation in which the pattern applies Problem : A short sentence or two raising the main difficulty. Forces : The issues or concerns to consider when solving the problem Solution : The recommended way to solve the problem in the given context. ‘ to balance the forces’ Antipatterns : (Optional) Solutions that are inferior or do not work in this context. Related patterns : (Optional) Patterns that are similar to this pattern. References : Who developed or inspired the pattern. University of Colombo School of Computing Advanced Software Engineering
  • 11.
    Types of softwarepatterns design patterns (software design) [Buschmann-POSA] architectural (systems design) design (micro-architectures) [Gamma-GoF] idioms (low level) analysis patterns (recurring & reusable analysis models) [Flower] organization patterns (structure of organizations/projects) process patterns (software process design) domain-specific patterns University of Colombo School of Computing Advanced Software Engineering
  • 12.
    Pattern language [Coplien]… is a structured collection of patterns that build on each other to transform needs and constraints into an architecture [Software Design Patterns: Common Questions and Answers] … defines collection of patterns and rules to combine them into an architectural style…describe software frameworks or families of related systems [Patterns Home Page ->Patterns Definitions] University of Colombo School of Computing Advanced Software Engineering
  • 13.
    Pattern catalogs andsystems pattern catalog … a collection of related patterns, where patterns are subdivided into small number of broad categories… pattern system … a cohesive set of related patterns, which work together to support the construction and evolution of hole architectures... University of Colombo School of Computing Advanced Software Engineering
  • 14.
    Types of DesignPatterns Creational Patterns to create objects of the right class for a problem, generally when instances of several different classes are available. Structural Patterns to form larger structures from individual parts, generally of different classes. Behavioral Patterns to describe interactions between objects. They focus on how objects communicate with each other. University of Colombo School of Computing Advanced Software Engineering
  • 15.
    Pattern Scope Patternscan be further divided into two categories Object Patterns specify relationships between objects. In general, the purpose of an object pattern is to allow the instances of different classes to be used in the same place in a pattern at runtime. Class Patterns specify the relationship between classes and their subclasses at compile time. University of Colombo School of Computing Advanced Software Engineering
  • 16.
    Design pattern catalog University of Colombo School of Computing Advanced Software Engineering
  • 17.
    The Singleton PatternIt is an object creational pattern. The intent of the Singleton pattern is twofold: Guarantee that a class has only one instance Provide access to that instance University of Colombo School of Computing Advanced Software Engineering
  • 18.
    The Singleton PatternContext : It is very common to find classes for which only one instance should exist ( singleton) Problem : How do you ensure that it is never possible to create more than one instance of a singleton class? Forces : The use of a public constructor cannot guarantee that no more than one instance will be created. The singleton instance must also be accessible to all classes that require it University of Colombo School of Computing Advanced Software Engineering
  • 19.
    Singleton Solution: Universityof Colombo School of Computing Advanced Software Engineering public class Singleton { static Singleton theInstance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return theInstance; } } « Singleton » theInstance getInstance
  • 20.
    Exercise Dual pattern Write a class called Dual that has exactly two instances, instance1 and instance2. Provide an access method that allows clients to retrieve both instances of the class. Do not allow clients directly access to the constructor. University of Colombo School of Computing Advanced Software Engineering
  • 21.
    The Abstraction-Occurrence PatternContext : Often in a domain model you find a set of related objects ( occurrences) . The members of such a set share common information but also differ from each other in important ways. Problem : What is the best way to represent such sets of occurrences in a class diagram?   Forces : You want to represent the members of each set of occurrences without duplicating the common information University of Colombo School of Computing Advanced Software Engineering
  • 22.
    Abstraction-Occurrence Solution:University of Colombo School of Computing Advanced Software Engineering TVSeries seriesName producer Episode number title storySynopsis * * * * * * «Occurrence» «Abstraction» * * * * * * Title name author LibraryItem barCodeNumber * * * * * * isbn publicationDate libOfCongress
  • 23.
    Abstraction-Occurrence Antipatterns:University of Colombo School of Computing Advanced Software Engineering name author LibraryItem barCodeNumber isbn publicationDate libOfCongress Title name author LibraryItem barCodeNumber isbn publicationDate libOfCongress name author LibraryItem barCodeNumber isbn publicationDate libOfCongress GulliversTravels MobyDick
  • 24.
    Abstraction-Occurrence Abstraction-Occurrence Squarevariant University of Colombo School of Computing Advanced Software Engineering ScheduledTrain number SpecificTrain date * * * * ScheduledLeg SpecificLeg actualDepTime * actualArrTime scheduledDepTime scheduledArrTime Station origin destination * *
  • 25.
    The General Hierarchy Pattern Context : Objects in a hierarchy can have one or more objects above them (superiors), and one or more objects below them (subordinates). Some objects cannot have any subordinates Problem : How do you represent a hierarchy of objects, in which some objects cannot have subordinates? Forces : You want a flexible way of representing the hierarchy that prevents certain objects from having subordinates All the objects have many common properties and operations University of Colombo School of Computing Advanced Software Engineering
  • 26.
    General Hierarchy Solution:University of Colombo School of Computing Advanced Software Engineering «subordinate» * «Node» «SuperiorNode» «NonSuperiorNode» 0..1 * supervises Manager Employee Technician Secretary 0..1 * contains Directory FileSystemItem File 0..1
  • 27.
    General Hierarchy Antipattern:University of Colombo School of Computing Advanced Software Engineering RockRecording BluesRecording ClassicalRecording JazzRecording MusicVideo VideoRecoding AudioRecording Recording
  • 28.
    The Player-Role PatternContext : A role is a particular set of properties associated with an object in a particular context. An object may play different roles in different contexts. Problem : How do you best model players and roles so that a player can change roles or possess multiple roles? University of Colombo School of Computing Advanced Software Engineering
  • 29.
    Player-Role Forces : It is desirable to improve encapsulation by capturing the information associated with each separate role in a class. You want to avoid multiple inheritance. You cannot allow an instance to change class Solution : University of Colombo School of Computing Advanced Software Engineering «Player» «Role1» «Role2» «AbstractRole»
  • 30.
    Player-Role Example 1:University of Colombo School of Computing Advanced Software Engineering
  • 31.
    Player-Role Example 2:University of Colombo School of Computing Advanced Software Engineering
  • 32.
    Player-Role Antipatterns: Mergeall the properties and behaviours into a single «Player» class and not have «Role» classes at all. Create roles as subclasses of the «Player» class. University of Colombo School of Computing Advanced Software Engineering
  • 33.
    The Observer PatternContext : When an association is created between two classes, the code for the classes becomes inseparable. If you want to reuse one class, then you also have to reuse the other. Problem : How do you reduce the interconnection between classes, especially between classes that belong to different modules or subsystems? Forces : You want to maximize the flexibility of the system to the greatest extent possible University of Colombo School of Computing Advanced Software Engineering
  • 34.
    Observer Solution: Universityof Colombo School of Computing Advanced Software Engineering WeatherViewer * * * * * * * Observers are notified when a new prediction is ready Forecaster Observable «ConcreteObservable» «ConcreteObserver» «Observable» addObserver notifyObservers «interface» «Observer» update * * * * * * * «interface» Observer
  • 35.
    University of ColomboSchool of Computing Advanced Software Engineering
  • 36.
    University of ColomboSchool of Computing Advanced Software Engineering
  • 37.
    Observer Antipatterns: Connectan observer directly to an observable so that they both have references to each other. Make the observers subclasses of the observable. University of Colombo School of Computing Advanced Software Engineering
  • 38.
    The Delegation PatternContext : You are designing a method in a class You realize that another class has a method which provides the required service Inheritance is not appropriate E.g. because the isa rule does not apply Problem : How can you most effectively make use of a method that already exists in the other class? Forces : You want to minimize development cost by reusing methods University of Colombo School of Computing Advanced Software Engineering
  • 39.
    Delegation Solution: Universityof Colombo School of Computing Advanced Software Engineering delegate.method(); « Delegate » « Delegator » delegatingMethod() { } delegatingMethod method LinkedList addFirst addLast addAfter removeFirst removeLast delete isEmpty Stack push pop isEmpty push() { list.addFirst(); }
  • 40.
    Delegation University ofColombo School of Computing Advanced Software Engineering Example: two levels of delegation
  • 41.
    Delegation Antipatterns Overusegeneralization and inherit the method that is to be reused Instead of creating a single method in the «Delegator» that does nothing other than call a method in the «Delegate consider having many different methods in the «Delegator» call the delegate’s method Access non-neighboring classes University of Colombo School of Computing Advanced Software Engineering return specificFlight.regularFlight.flightNumber(); return getRegularFlight().flightNumber();
  • 42.
    The Adapter PatternContext : You are building an inheritance hierarchy and want to incorporate it into an existing class. The reused class is also often already part of its own inheritance hierarchy. Problem : How to obtain the power of polymorphism when reusing a class whose methods have the same function but not the same signature as the other methods in the hierarchy? Forces : You do not have access to multiple inheritance or you do not want to use it. University of Colombo School of Computing Advanced Software Engineering
  • 43.
    Adapter Solution: Universityof Colombo School of Computing Advanced Software Engineering «Adaptee» adaptedMethod «Superclass» polymorphicMethod «Adapter» polymorphicMethod() return adaptee.adaptedMethod(); { }
  • 44.
    Adapter Example: Universityof Colombo School of Computing Advanced Software Engineering TimsTorus calcVolume ThreeDShape volume Sphere Torus volume() return TimsTorus.calcVolume(); { }
  • 45.
    Adapters Other NamesWrappers Examples Java Wrapper classes Integer, Float, Double Related Patterns Façade, Read Only Interface, Proxy University of Colombo School of Computing Advanced Software Engineering
  • 46.
    The Façade PatternContext : Often, an application contains several complex packages. A programmer working with such packages has to manipulate many different classes Problem : How do you simplify the view that programmers have of a complex package? Forces : It is hard for a programmer to understand and use an entire subsystem If several different application classes call methods of the complex package, then any modifications made to the package will necessitate a complete review of all these classes. University of Colombo School of Computing Advanced Software Engineering
  • 47.
    Façade Solution: Universityof Colombo School of Computing Advanced Software Engineering «PackageClass3» «PackageClass2» «PackageClass1» * * * * * * RegularFlight * * * * * * Reservation Airline findFlight makeBooking deleteBooking «Facade»
  • 48.
    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 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 otherwise modify an instance variable is required, then it has to return a new instance of the class. University of Colombo School of Computing Advanced Software Engineering
  • 49.
    The Read-only InterfacePattern Context : 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 some classes see a class as read-only whereas others are able to make modifications? Forces : Restricting access by using the public , protected and private keywords is not adequately selective. Making access public makes it public for both reading and writing University of Colombo School of Computing Advanced Software Engineering
  • 50.
    Read-only Interface Solution:University of Colombo School of Computing Advanced Software Engineering «UnprivilegedClass» * * * * * * «Mutator» «Mutable» attribute «private» getAttribute setAttribute «interface» «ReadOnlyInterface» getAttribute * * * * *
  • 51.
    Read-only Interface Example:University of Colombo School of Computing Advanced Software Engineering Mutableperson firstName lastName setFirstName setLastName getName «interface» Person getName
  • 52.
    The Proxy PatternContext : Often, it is time-consuming and complicated to create instances of a class ( heavyweight classes). There is a time delay and a complex mechanism involved in creating the object in memory Problem : How to reduce the need to create instances of a heavyweight class? Forces : We want all the objects in a domain model to be available for programs to use when they execute a system’s various responsibilities. It is also important for many objects to persist from run to run of the same program University of Colombo School of Computing Advanced Software Engineering
  • 53.
    Proxy Solution: Universityof Colombo School of Computing Advanced Software Engineering «interface» «ClassIF» * * * * * * * «Client» «HeavyWeight» «Proxy»
  • 54.
    Proxy Example: Universityof Colombo School of Computing Advanced Software Engineering «interface» ListIF The list elements will be loaded into local memory only when needed. ListProxy PersistentList «interface» Student PersistentStudent StudentProxy
  • 55.
    Difficulties and RisksWhen Creating Class Diagrams Patterns are not a panacea : Whenever you see an indication that a pattern should be applied, you might be tempted to blindly apply the pattern. However this can lead to unwise design decisions . Resolution: Always understand in depth the forces that need to be balanced, and when other patterns better balance the forces. Make sure you justify each design decision carefully. University of Colombo School of Computing Advanced Software Engineering
  • 56.
    Difficulties and RisksWhen Creating Class Diagrams Developing patterns is hard Writing a good pattern takes considerable work. A poor pattern can be hard to apply correctly Resolution: Do not write patterns for others to use until you have considerable experience both in software design and in the use of patterns. Take an in-depth course on patterns. Iteratively refine your patterns, and have them peer reviewed at each iteration. University of Colombo School of Computing Advanced Software Engineering

Editor's Notes

  • #5 As mentioned before, the current use of the term "pattern" is derived from the writings of the architect Christopher Alexander who has written several books on the topic as it relates to urban planning and building architecture (list of books). Patterns in software first became popular with the wide acceptance of the book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (frequently referred to as the Gang of Four or just GoF). Other recent books that have helped popularize patterns are: Pattern-Oriented Software Architecture: A System of Patterns ( also called the POSA book ) by Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, and Michael Stal (sometimes called the Siemens Gang of Five or just GoV); and the books Pattern Languages of Program Design and Pattern Languages of Program Design 2, which are selected papers from the first and second conferences on Patterns Languages of Program Design (PLoP or PLoPD). Many of these books are part of the Software Patterns Series from Addison-Wesley.
  • #6 It is unavoidable to mention what Alexander says about patterns, since the origin of design patterns lies in work done by him in late 70is. Although Alexander was talking about patterns in buildings, the core of patterns in object-oriented design and building is a solution to a problem in a context. In "Understanding and Using Patterns in Software Development", Dirk Riehle and Heinz Zullighoven give a nice definition of the term "pattern" which is very broadly applicable. Coplein in his paper “Software Design Patterns: Common questions and Answers” refers to patterns as both the thing and the instructions for making the thing. Basically, pattern can be viewed as a particular prose form of recording design information such that designs which have worked well in the past can be applied again in similar situations in the future. (Beck, Coplien - “Industrial experience with design patterns”
  • #8 Patterns provide a common vocabulary for designers to communicate, document, and explore design alternatives (Gamma93-paper). Consequently enabling effective communicating of complex concepts between designers. Patterns capture solutions and essential parts of design in a compact form. Pattern describe software abstractions, ensuring vide applicability, but a pattern may provide hints about potential implementation issues). Simply said, patterns help designer get a design “right” faster. Patterns are not necessarily object.oriented, and patterns can be found in a variety of software systems, independent of the methods used in developing those systems (Coplien, Industrial experience) However, a pattern is not an implementation. It describes when, why, and how to go about creating an implementation or other engineering product. Also, patterns do not solve all design problems.
  • #9 Patterns provide a common vocabulary for designers to communicate, document, and explore design alternatives (Gamma93-paper). Consequently enabling effective communicating of complex concepts between designers. Patterns capture solutions and essential parts of design in a compact form. Pattern describe software abstractions, ensuring vide applicability, but a pattern may provide hints about potential implementation issues). Simply said, patterns help designer get a design “right” faster. Patterns are not necessarily object.oriented, and patterns can be found in a variety of software systems, independent of the methods used in developing those systems (Coplien, Industrial experience) However, a pattern is not an implementation. It describes when, why, and how to go about creating an implementation or other engineering product. Also, patterns do not solve all design problems.
  • #10 Every pattern has these essential elements: Context - refers to a recurring set of situations in which the pattern applies. Problem -refers to a set of forces -- goals and constraints -- that occur in this context. (describes when to apply the pattern) Solution -refers to a design form or design rule that someone can apply to resolve these forces. (describes the elements that make up design, their relationships, responsibilities and collaboration)
  • #12 Much of the initial patterns focus in the software community has been on design patterns. The patterns in the [GoF] book are object-oriented design patterns. However, there are many other kinds of software patterns besides design patterns. For example, Martin Fowler has written a book of Analysis Patterns. Patterns cover all aspects of software engineering including: development organization, software process, project planning, requirements engineering, and software configuration, management (just to name a few). Presently however, design patterns still seem to be the most popular (though organization patterns seem to be gaining momentum). ---- The difference between these three kinds of design patterns are in their corresponding levels of abstraction and detail. Architectural patterns are high-level strategies that concern large-scale components and the global properties and mechanisms of a system. They have wide-sweeping implications which affect the overall skeletal structure and organization of a software system. Design patterns are medium-scale tactics that flesh out some of the structure and behavior of entities and their relationships. They do not influence overall system structure, but instead define micro-architectures of subsystems and components. Idioms are paradigm-specific and language-specific programming techniques that fill in low-level internal or external details of a component's structure or behavior.
  • #13 In the Patterns Definitions section of the Patterns Home Page, Cope defines a pattern language as follows: A pattern language defines a collection of patterns and the rules to combine them into an architectural style. Pattern languages describe software frameworks or families of related systems. Cope gives a slightly different definition in "Software Design Patterns: Common Questions and Answers": A pattern language is a structured collection of patterns that build on each other to transform needs and constraints into an architecture. A pattern language includes rules and guidelines which explain how and when to apply its patterns to solve a problem which is larger than any individual pattern can solve. These rules and guidelines suggest the order and granularity for applying each pattern in the language. A pattern language may be regarded as a lexicon of patterns plus a grammar that defines how to weave them together into valid sentences (or artful tapestries if you will). Ideally, good pattern languages are generative, capable of generating all the possible sentences from a rich and expressive pattern vocabulary.
  • #14 The authors of [POSA] have classified different kinds of pattern collections that possess varying degrees of structure and interaction into pattern catalogs, systems, and languages: Pattern Catalogs A pattern catalog is a collection of related patterns (perhaps only loosely or informally related). It typically subdivides the patterns into at least a small number of broad categories and may include some amount of cross referencing between patterns. Pattern Systems A pattern system is a cohesive set of related patterns which work together to support the construction and evolution of whole architectures. It describes many interrelationships between the patterns and their groupings and how they may be combined and composed to solve more complex problems. The primary difference between the pattern system and a pattern language is that, ideally, pattern languages are computationally complete, showing all possible combinations of patterns and their variations to produce complete architectures. In practice however, the difference between pattern systems and pattern languages can be extremely difficult to ascertain.
  • #15 Structural patterns form larger structures from individual parts, generally of different classes. Structural patterns vary a great deal depending on what sort of structure is being created for what purpose. to describe interactions between objects. They focus on how objects communicate with each other. They can reduce complex flow charts to mere interconnections between objects of various classes.
  • #17 In Gamma’s book, patterns are classified by two criteria. First is Purpose, which reflects what pattern does. Patterns can have either creational, structural, or behavioral purpose. Creational patterns concern the process of object creation. Structural patterns deal with the composition of classes or objects. Behavioral patterns characterize the ways in which classes or objects interact and distribute responsibility. The second criterion is scope, which specifies whether the pattern applies primarly on classes or objects. Class patterns deal with relationships between classes and their sub-classes. These relationships are established through inheritance, so they are static (fixed at compile time). Object patterns deal with object relationships, which can be changed at run-time and are more dynamic. (petterns labeled as class patterns are those that focus on class relationships.
  • #22 Example: 1. All episodes of
  • #24 Real mistakes made by beginners
  • #34 If u compile one class, then other one also have to be modified if it is a bi-directional association relationship.
  • #39 Structural Pattern
  • #43 Another gan of four pattern, also known as wrappers Structural Pattern