P Training Presentation


Published on

1 Comment
  • Hi,
    Gaurav your Design patterns ppt is very usefull.Could you please send it through my mail below...
    rajakannan168@gmail.com. Or provide me access to dowload the ppt.
    Thanks in advance.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

P Training Presentation

  1. 1. Java Design Patterns By Gaurav Tyagi
  2. 2. Day 1 - Agenda <ul><li>UML & Design Principles </li></ul><ul><li>Introduction to Java Design Patterns </li></ul><ul><li>Creational Patterns </li></ul><ul><ul><li>Singleton </li></ul></ul><ul><ul><li>Factory Method </li></ul></ul><ul><ul><li>Prototype </li></ul></ul><ul><ul><li>Abstract Factory </li></ul></ul>
  3. 3. UML – Elements <ul><li>Class </li></ul><ul><li>Attributes </li></ul><ul><li>Operations </li></ul><ul><li>Relationships </li></ul><ul><ul><li>IS-A </li></ul></ul><ul><ul><ul><li>Inheritance </li></ul></ul></ul><ul><ul><li>HAS-A </li></ul></ul><ul><ul><ul><li>Composition/Aggregation </li></ul></ul></ul>
  4. 4. Design Principles <ul><li>Encapsulation </li></ul><ul><ul><li>Separate what varies from what stays the same </li></ul></ul><ul><li>Program to an interface, not an implementation </li></ul><ul><ul><li>Remember Polymorphism ?? </li></ul></ul><ul><li>Favor Object composition over Class Inheritance </li></ul><ul><li>Delegation </li></ul><ul><li>Strive for loosely couples designs between objects that interact </li></ul>
  5. 5. Design Principles – Open-Closed Principle <ul><li>New changes should be added with minimum changes to the existing code </li></ul><ul><li>Intent </li></ul><ul><ul><li>Classes should be open for extension and closed for modification </li></ul></ul><ul><li>Should be applied to those areas which are likely to change </li></ul><ul><li>Do not apply to every area of the system </li></ul>
  6. 6. Design Principle – Open-Closed Principle <ul><li>class GraphicEditor { public void drawShape(Shape s) { if (s.m_type==1) drawRectangle(s); else if (s.m_type==2) drawCircle(s); public void drawCircle(Circle r) {....} public void drawRectangle(Rectangle r) {....} } class Shape { int m_type; } class Rectangle extends Shape { Rectangle() { super.m_type=1; } } class Circle extends Shape { Circle() { super.m_type=2; } } </li></ul>
  7. 7. Design Principle – Open Closed Principle <ul><li>class GraphicEditor { public void drawShape(Shape s) { s.draw(); } } class Shape { abstract void draw(); } class Rectangle extends Shape { public void draw() { // draw the rectangle } } </li></ul>
  8. 8. Design Principle – Dependency Inversion <ul><li>Depend upon abstractions </li></ul><ul><li>Do not depend on concrete classes </li></ul><ul><li>High level components should NOT depend upon low level components </li></ul><ul><li>Write code so that we depend upon abstractions </li></ul><ul><ul><li>High Level Classes --> Abstraction Layer --> Low Level Classes </li></ul></ul>
  9. 9. Design Principle – Dependency Inversion <ul><li>class Worker { public void work() { // ....working } } class Manager { Worker m_worker; public void setWorker(Worker w) { m_worker=w; } public void manage() { m_worker.work(); } } class SuperWorker { public void work() { //.... working much more } } </li></ul>
  10. 10. Design Principle – Dependency Inversion <ul><li>interface IWorker { public void work(); } class Worker implements IWorker{ public void work() { // ....working } } class SuperWorker implements IWorker{ public void work() { //.... working much more } } class Manager { IWorker m_worker; public void setWorker(IWorker w) { m_worker=w; } public void manage() { m_worker.work(); } } </li></ul>
  11. 11. Design Principle – Interface Segregation <ul><li>Clients should not be forced to implement interfaces that they don’t use </li></ul><ul><li>Instead of one fat interface, create many small interfaces </li></ul><ul><li>If design is already done with fat interfaces – use adapter pattern </li></ul>
  12. 12. Design Principle – Principle of least knowledge <ul><li>Talk only to your immediate friends </li></ul><ul><li>For any object, limit the number of classes it interacts with </li></ul><ul><li>Prevents changes from cascading to other parts of the system </li></ul><ul><li>We should only invoke methods that belong to </li></ul><ul><ul><li>The object itself </li></ul></ul><ul><ul><li>Objects passed in as parameter to the method </li></ul></ul><ul><ul><li>Any object that method creates or instantiates </li></ul></ul><ul><ul><li>Any components of the object </li></ul></ul>
  13. 13. Design Principle - Single Responsibility <ul><li>A class should have only one reason to change </li></ul><ul><li>More than one responsibility implies more than one area of change </li></ul><ul><li>Cohesion </li></ul><ul><ul><li>High Cohesion: Classes or modules designed around a set of related functions </li></ul></ul><ul><ul><li>Low Cohesion: Classes or modules designed around a set of unrelated functions </li></ul></ul><ul><li>Classes that adhere to the principle tend to have high cohesion </li></ul>
  14. 14. Don’t Repeat yourself (DRY) <ul><li>One Requirement in one place </li></ul><ul><li>Each piece of information and behavior in a single sensible place </li></ul>
  15. 15. Liskov Substitution Principle (LSP) <ul><li>Subtypes must be substitutable for their base types </li></ul>
  16. 16. What are Design Patterns ? <ul><li>Design Pattern </li></ul><ul><ul><li>&quot;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” </li></ul></ul><ul><li>Class Patterns </li></ul><ul><ul><li>Deal with relationships between classes and their sub-classes </li></ul></ul><ul><ul><ul><li>Static and established at compile time </li></ul></ul></ul><ul><li>Object Patterns </li></ul><ul><ul><li>Deal with object relationships which are more dynamic and can change at runtime </li></ul></ul>
  17. 17. Which pattern to use ? <ul><li>Creating an object by specifying a class explicitly </li></ul><ul><li>Dependence on specific operations </li></ul><ul><li>Dependence on hardware and software platform </li></ul><ul><li>Dependence on object representations or implementations </li></ul><ul><li>Algorithmic dependencies </li></ul><ul><li>Tight Coupling </li></ul><ul><li>Extending functionality by sub-classing </li></ul><ul><li>Inability to alter classes conveniently </li></ul>
  18. 18. Types of Java Pattern <ul><li>Creational Patterns </li></ul><ul><ul><li>Concern with the process of Object Creation </li></ul></ul><ul><ul><ul><li>Class Patterns </li></ul></ul></ul><ul><ul><ul><ul><li>Defer some part of object creation to subclasses </li></ul></ul></ul></ul><ul><ul><ul><li>Object Patterns </li></ul></ul></ul><ul><ul><ul><ul><li>Defer creation to another object </li></ul></ul></ul></ul><ul><li>Structural Patterns </li></ul><ul><ul><li>Deal with composition of classes or objects </li></ul></ul><ul><ul><ul><li>Class Patterns </li></ul></ul></ul><ul><ul><ul><ul><li>Use inheritance to compose classes </li></ul></ul></ul></ul><ul><ul><ul><li>Object Patterns </li></ul></ul></ul><ul><ul><ul><ul><li>Describe ways to assemble objects </li></ul></ul></ul></ul>
  19. 19. Types of Java Patterns <ul><li>Behavioral Patterns </li></ul><ul><ul><li>Concerned with algorithms and the assignment of responsibilites between objects </li></ul></ul><ul><ul><ul><li>Class Patterns </li></ul></ul></ul><ul><ul><ul><ul><li>Use inheritance to describe algorithms and flow of control </li></ul></ul></ul></ul><ul><ul><ul><li>Object Patterns </li></ul></ul></ul><ul><ul><ul><ul><li>Describe how a group of objects cooperate to perform a task that no single object can carry out alone </li></ul></ul></ul></ul>
  20. 20. Creational Patterns
  21. 21. Singleton Pattern <ul><li>Important for some classes to have exactly one instance </li></ul><ul><ul><li>Ex: For many printers, there should be only one printer spooler </li></ul></ul><ul><li>Make a class itself responsible for keeping track of its sole instance </li></ul><ul><li>Structure </li></ul>Singleton static Instance() Singleton Operation() GetSingletonData() static uniqueInstance singletonData return uniqueInstance
  22. 22. Singleton Pattern <ul><li>Pros/Cons </li></ul><ul><ul><li>Controlled access to sole instance </li></ul></ul><ul><ul><li>Reduced Name space </li></ul></ul><ul><li>Implementation </li></ul><ul><ul><li>Ensuring a unique instance </li></ul></ul><ul><ul><ul><li>final class RemoteConnection { </li></ul></ul></ul><ul><ul><ul><ul><li>private Connect con; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>private static RemoteConnection rc = new RemoteConnection(connection); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>private RemoteConnection(Connect c) { con = c; .... } </li></ul></ul></ul></ul><ul><ul><ul><ul><li>public static RemoteConnection getRemoteConnection() { return rc; } </li></ul></ul></ul></ul><ul><ul><ul><ul><li>public void setConnection(Connect c) { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>this(c); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  23. 23. Singleton in a Distributed Environment <ul><li>Singleton is one instance per virtual machine/class loader </li></ul><ul><li>A singleton cannot be shared across multiple JVMs. </li></ul>
  24. 24. Singleton Pattern – Sample Singleton ThreadSafe Singleton Classic Singleton Preferred
  25. 25. Factory Method <ul><li>To be used when it must be decided at runtime which one of the several compatible classes is to be instantiated </li></ul><ul><li>Instantiation in public can lead to coupling problems </li></ul><ul><li>All products implement the same interface </li></ul>Abstract Class Client class Concrete class Product Product Class
  26. 26. Factory Method <ul><li>Advantage </li></ul><ul><ul><li>Provides hooks for subclasses </li></ul></ul><ul><ul><li>Connects parallel class hierarchies </li></ul></ul><ul><li>Disadvantage </li></ul><ul><ul><li>Clients have to subclass the creator class just to create a particular concrete product object </li></ul></ul><ul><ul><li>Avoid subclass with templates </li></ul></ul>Figure TextFigure Linefigure Client Manipulator Text Manipulator Line Manipulator
  27. 27. Factory Method - Implementation <ul><li>Parameterized Factory Methods </li></ul><ul><ul><li>Factory takes a parameter as input </li></ul></ul><ul><ul><li>Creates multiple kinds of products </li></ul></ul><ul><li>Creator class is abstract and provides no implementation for the factory method </li></ul><ul><li>Creator is a concrete class and provides a default implementation of the factory </li></ul>
  28. 28. Class Problem <ul><ul><li>A toy manufacturing company needs to produce differently shaped blocks. These toys could be plastic, wooden or steel. All toys have similar characteristic but different shapes. The software which needs to create the 3D design of these toy should be able to draw them and then pass it to a controller which converts it to a bit string and sends it to the appropriate machine for manufacture. Design a UML based solution and come up with a class diagram. </li></ul></ul>
  29. 29. Factory Method – Sample Code Toy Bus Cycle SimpleToyFactory Car ToyStore Scooter
  30. 30. Prototype <ul><li>Specifying the kind of objects to create using a Prototypical instance and creating objects using this prototype </li></ul><ul><li>When the classes to instantiate are specified at runtime </li></ul><ul><li>To avoid building a class hierarchy of factories that parallels the class hierarchy of products </li></ul><ul><li>Should be considered when system needs to create new objects of many types in a complex class hierarchy </li></ul>
  31. 31. Prototype - Structure Client Prototype clone() ConcretePrototype1 clone() ConcretePrototype2 clone()
  32. 32. Prototype <ul><li>Advantages of Cloning(Prototype) over Subclassing(Factory) </li></ul><ul><ul><li>Factory Method: Creation through inheritance </li></ul></ul><ul><ul><li>Prototype: Creation through delegation </li></ul></ul><ul><ul><ul><li>Providing a &quot;create based on existing state&quot; behavior allows programs to perform operations like user-driven copy, and to initialize objects to a state that has been established through use of the system. </li></ul></ul></ul><ul><li>Benefits & Drawbacks </li></ul><ul><ul><li>Shallow Copy </li></ul></ul><ul><ul><li>Deep Copy </li></ul></ul><ul><ul><li>Adding and Removing Products at runtime </li></ul></ul><ul><ul><li>Specifying new objects by varying value </li></ul></ul><ul><ul><li>Reduced Subclasses </li></ul></ul>
  33. 33. Prototype <ul><li>Pattern Variants </li></ul><ul><ul><li>Copy Constructor </li></ul></ul><ul><ul><ul><li>public class Prototype { </li></ul></ul></ul><ul><ul><ul><li>private int someData; // some more data </li></ul></ul></ul><ul><ul><ul><li>public Prototype(Prototype original) { </li></ul></ul></ul><ul><ul><ul><li>super(); </li></ul></ul></ul><ul><ul><ul><li>this.someData = original.someData; </li></ul></ul></ul><ul><ul><ul><li>//copy the rest of the data </li></ul></ul></ul><ul><ul><ul><li>} // rest of code </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>Clone method </li></ul></ul><ul><ul><li>Prototype manager </li></ul></ul><ul><ul><ul><li>Registry for prototypes when the number of prototypes isn’t fixed </li></ul></ul></ul>
  34. 34. Prototype - Sample Bus Car Cycle Scooter SimpleToyFactory Toy ToyStore
  35. 35. Abstract Factory Pattern <ul><li>Motivation </li></ul><ul><ul><li>Different look and feel define different appearances and behavior </li></ul></ul><ul><li>Applicability </li></ul><ul><ul><li>System should be independent of how its products are created, composed and represented </li></ul></ul><ul><ul><li>System should be configured with one of multiple families of products </li></ul></ul><ul><ul><li>A family of related product objects is designed to be used together </li></ul></ul><ul><ul><li>Provide a class of library of products and only expose their interfaces, not their implementations </li></ul></ul>
  36. 36. Abstract Factory Pattern - Structure CreateProductA() CreateProductB() AbstractFactory createProductA() createProductB() ConcreteFactory1 createProductA() createProductB() ConcreteFactory2 Client AbstractProductA AbstractProductB ProductA1 ProductA2 ProductB1 ProductB2
  37. 37. Abstract Factory Pattern <ul><li>Pros/Cons </li></ul><ul><ul><li>Isolates concrete Classes </li></ul></ul><ul><ul><li>Makes exchanging product Families easy </li></ul></ul><ul><ul><li>Promotes consistency among products </li></ul></ul><ul><ul><li>Supporting new kind of products is difficult </li></ul></ul><ul><li>Implementation </li></ul><ul><ul><li>Factories as Singletons </li></ul></ul><ul><ul><li>Product Creation </li></ul></ul><ul><ul><ul><li>Factory Method for each product </li></ul></ul></ul><ul><ul><ul><ul><li>Requires a new factory for each product family </li></ul></ul></ul></ul><ul><ul><ul><li>For mulitple product families, use Prototype pattern. </li></ul></ul></ul><ul><ul><ul><ul><li>Eliminates the need for a new concrete factory class for each product family </li></ul></ul></ul></ul>
  38. 38. Exercise <ul><li>The toy company would like to produce different parts of each toy. Each toy part will have its own controller i.e. plastic controller, steel controller & concrete controller which will create the bit string and send it to the appropriate machine. Design a UML based solution and come up with a class diagram. </li></ul>
  39. 39. Abstract Factory Pattern – Sample Code PlasticDoor Accelerator Door PlasticAccelerator PlasticSeat PlasticToyFactory Seat ToyPartsFactory WoodenAccelerator WoodenDoor WoodenSeat WoodenToyFactory
  40. 40. Problem of the Day <ul><li>A software system for handling student results has this requirement. There are two streams - Science & Commerce. Both streams have different subjects and they don’t overlap. Each science student has 4 subjects while commerce student has 3 subjects. For each subject, marks are awarded out of 100. Every subject has a final mark. The final mark is used for calculating the grade. Give a UML based Design. </li></ul>
  41. 41. Day 2 Agenda <ul><li>Builder Pattern </li></ul><ul><li>Creational Patterns - Summary </li></ul><ul><li>Overview of Structural Patterns </li></ul><ul><ul><li>Adapter </li></ul></ul><ul><ul><li>Facade </li></ul></ul><ul><ul><li>Bridge </li></ul></ul><ul><ul><li>Composite </li></ul></ul>
  42. 42. Builder Pattern <ul><li>Intent </li></ul><ul><ul><li>Separate the construction of a complex object from its representation so that the same construction process can create different representations. </li></ul></ul><ul><ul><li>Parse a complex representation, create one of several targets. </li></ul></ul><ul><li>Applicability </li></ul><ul><ul><li>The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled </li></ul></ul><ul><ul><li>The construction process must allow different representations for the object that's constructed </li></ul></ul>
  43. 43. Builder Pattern - Structure Director Builder ConcreteBuilder builder Construct() BuildPart() BuildPart() GetResult()
  44. 44. Builder Pattern - Consequences <ul><li>Lets you vary a products internal representation </li></ul><ul><li>Isolates code for construction and representation </li></ul><ul><li>Gives you finer control over construction process </li></ul>
  45. 45. Class Problem <ul><ul><li>A website MakeMyYatra.com helps users to plan their vacations. The vacation could include travel reservations, hotel reservations, admission tickets to events, special privileges, etc for some specified dates. Design a UML based class diagram for this requirement. Assume the following classes: Vacation, Day, Hotel, Flight, Reservation </li></ul></ul>
  46. 46. Builder Pattern - Implementation Builder Day Vacation VacationBuilder
  47. 47. Rules of Thumb <ul><li>Builder & Abstract Factory </li></ul><ul><ul><li>Common Interface </li></ul></ul><ul><li>Abstract Factory might store a set of Prototypes from which to clone and return product objects. </li></ul><ul><li>Abstract Factory, Builder, and Prototype can use Singleton in their implementations. </li></ul>
  48. 48. Creational Patterns - Summary <ul><li>Factory Method: creation through inheritance. Protoype: creation through delegation. </li></ul><ul><li>Prototype doesn’t require sub-classing, but it does require an “initialize” operation. Factory Method requires sub-classing, but doesn’t require Initialize. </li></ul><ul><li>Prototype is unique among the other creational patterns in that it doesn’t require a class – only an object. </li></ul>
  49. 49. Strutural Patterns
  50. 50. Adapter Pattern <ul><li>Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. </li></ul><ul><li>Interface an old component to a new system </li></ul><ul><li>Need to use several existing subclasses </li></ul><ul><li>Example </li></ul><ul><ul><li>AC Power adapter </li></ul></ul>
  51. 51. Adapter Pattern Vendor System Adapter Existing Class Vendor System Existing Class
  52. 52. Adapter Pattern - Structure <ul><li>Class Adapter </li></ul><ul><li> Using Inheritance </li></ul><ul><li>Object Adapter </li></ul><ul><ul><li>Using Delegation </li></ul></ul>Client Target Adaptee Adapter Request() specificReq() Request() Call specificReq() Client Target Request() Adaptee specificReq() Adapter Request() Call adaptee->specificReq()
  53. 53. Adapter Pattern <ul><li>Trade-offs between class and object adapters </li></ul><ul><ul><li>Class Adapter </li></ul></ul><ul><ul><ul><li>Adapts Adaptee to Target by committing to a concrete Adapter class </li></ul></ul></ul><ul><ul><ul><li>Lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of Adaptee. </li></ul></ul></ul><ul><ul><ul><li>Introduces only one object, and no additional pointer indirection is needed to get to the adaptee </li></ul></ul></ul><ul><ul><li>Object Adapter </li></ul></ul><ul><ul><ul><li>Lets a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses </li></ul></ul></ul><ul><ul><ul><li>Makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter </li></ul></ul></ul>
  54. 54. Adapter Pattern – Pluggable Adapters <ul><li>They are classes with built-in interface adaptation </li></ul><ul><ul><li>Example: TreeDisplay widget </li></ul></ul><ul><li>Implementation approaches </li></ul><ul><ul><li>Using abstract Operations </li></ul></ul>TreeDisplay (Client, Target) GetChildren(Node) CreateGraphicalNode() BuildTree(Node n) DirectoryTreeDisplay (Adapter) GetChildren(Node) CreateGraphicalNode() FileSystemEntity (Adaptee) GetChildren(n) For each child { AddGraphicNode( createGraphicalNode()) BuildTree(Child) }
  55. 55. Adapter Pattern – Pluggable Adapters <ul><li>Using delegate objects </li></ul>TreeDisplay (Client) GetChildren(Node) CreateGraphicalNode() BuildTree(Node n) DirectoryBrowser (Adapter) GetChildren(Node) CreateGraphicalNode() Delegate->GetChildren(n) For each child { AddGraphicNode( Delegate.createGraphicalNode()) BuildTree(Child) } FileSystemEntity (Adaptee) TreeAccessDelegate (Target) GetChildren(Node) CreateGraphicalNode() delegate
  56. 56. Adapter Pattern <ul><li>How much adapting to do ? </li></ul><ul><li>Does an adapter always wrap one and only one class ? </li></ul>
  57. 57. Class Problem <ul><li>Adapt an Enumeration to an Iterator </li></ul><ul><li>Enumeration Interface </li></ul><ul><ul><li>hasMoreElements() </li></ul></ul><ul><ul><li>nextElement() </li></ul></ul><ul><li>Iterator </li></ul><ul><ul><li>hasNext() </li></ul></ul><ul><ul><li>Next() </li></ul></ul><ul><ul><li>Remove() </li></ul></ul>
  58. 58. Adapter Pattern - Sample Bombay Duck Client Duck Turkey Turkey WildTurkey
  59. 59. Facade Pattern <ul><li>Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. </li></ul><ul><li>Wrap a complicated subsystem with a simpler interface. </li></ul><ul><li>Example </li></ul><ul><ul><li>Home Theatre, Compiler </li></ul></ul>
  60. 60. Facade Pattern Facade
  61. 61. Façade Pattern - Benefits <ul><li>Decouples clients from subsystem components </li></ul><ul><ul><li>Clients only code to facade </li></ul></ul><ul><li>Promotes weak coupling between the subsystem and its clients </li></ul><ul><li>Doesn’t encapsulate sub-system. Only provides a simpler interface </li></ul><ul><ul><li>The subsystem is still accessible for direct use </li></ul></ul>
  62. 62. Façade Patterns - Implementation <ul><li>Can facade add its own functionality ? </li></ul><ul><li>Number of facades </li></ul><ul><li>Façade and adapters may wrap multiple classes, but the difference is in their intent </li></ul><ul><ul><li>Façade simplifies an interface </li></ul></ul><ul><ul><li>Adapter converts the target interface into something that client is expecting </li></ul></ul>
  63. 63. Façade Pattern - Sample Projector Amplifier CdPlayer DvdPlayer HomeTheatreFacade HomeTheatreClient PopcornPopper Tuner Screen TheatreLights
  64. 64. Decorator Pattern <ul><li>Attach/Detach additional responsibilities to an object dynamically. </li></ul><ul><li>Provide a flexible alternative to sub-classing for extending functionality. </li></ul><ul><li>Wrapping a gift, putting it in a box, and wrapping the box. </li></ul><ul><li>New behavior is acquired by composition and NOT by subclassing </li></ul>
  65. 65. Decorator Pattern Component Concrete Component Decorator Component Decorator ComponentB Decorator ComponentA component
  66. 66. Decorator Pattern <ul><li>More flexibility than static inheritance </li></ul><ul><li>Lots of little objects </li></ul><ul><li>Implementation </li></ul><ul><ul><li>Interface Conformance </li></ul></ul><ul><ul><li>Keeping component classes light weight </li></ul></ul>
  67. 67. Real world Decorator <ul><li>Java.io package is largely based on decorator </li></ul><ul><li>FileInputStream </li></ul><ul><ul><li>Decorated by BufferedInputStream </li></ul></ul><ul><ul><ul><li>Decorated by LineNumberInputStream </li></ul></ul></ul>
  68. 68. Class Problem <ul><li>MyCafe provides a range of coffee beverages. It’s a fastest growing coffee shop in town. Due to overwhelming response from its customers, it’s scrambling to update its ordering systems. In addition to coffee, customers can also add lot of condiments like milk, soy, mocha etc. MyCafe charges a bit for each one of these. They need an effective design to compute the cost of a beverage containing any type of condimentCreate a UML based diagram for these requirements. Assume the following initial classes (Feel Free to add more classes) </li></ul><ul><ul><li>Beverages: HouseBlend, Espresso, DarkRoast, Decaf </li></ul></ul><ul><ul><li>Condiments: Milk, Soy, Whip, Mocha </li></ul></ul>
  69. 69. Decorator Pattern - Sample Beverage CondimentDecorator DarkRoast Decaf Espresso HouseBlend Milk Mocha Soy StarbucksCoffee Whip
  70. 70. Composite Pattern <ul><li>Compose objects into tree structures to represent part-whole hierarchies </li></ul><ul><li>Recursive composition </li></ul>Picture Text Rectangle Line Rectangle Line Picture
  71. 71. Composite Pattern Client Component doThis() Leaf Composite doThis() Add(Component) Remove(Component) GetChild(Int) children doThis()
  72. 72. Composite Pattern - Consequences <ul><li>Defines class hierarchies consisting of primitive components and composite components </li></ul><ul><li>Clients can treat individual & composite object uniformly </li></ul><ul><li>Makes it easier to add new kind of components </li></ul>
  73. 73. Composite Pattern - Implementation <ul><li>Maintaining references from child components to their parent </li></ul><ul><li>Sharing components </li></ul><ul><li>Maximizing the Component interface </li></ul><ul><li>Declaring the child management operations </li></ul>
  74. 74. Class Problem <ul><ul><li>A newly opened restaurant wants to create a new menu. There are menus for breakfast, lunch & dinner. Each menu has sub-categories such as sub-menu for pancakes in breakfast, sub-menu for chicken and vegetable dishes in lunch & dinner and a sub-menu for desserts. Any menu can be extended further with more categories. Design a UML based class diagram. </li></ul></ul>
  75. 75. Composite Pattern - Sample Menu MenuComponent MenuItem MenuTestClient
  76. 76. Problem of the day <ul><li>MyCafe provides a range of coffee beverages. It’s a fastest growing coffee shop in town. Due to overwhelming response from its customers, it’s scrambling to update its ordering systems. In addition to coffee, customers can also add lot of condiments like milk, soy, mocha etc. MyCafe charges a bit for each one of these. They need an effective design to compute the cost of a beverage containing any type of condiment. Create a UML based diagram for these requirements. Assume the following classes </li></ul><ul><ul><ul><li>Beverages: HouseBlend, Espresso, DarkRoast, Decaf </li></ul></ul></ul><ul><ul><ul><li>Condiments: Milk, Soy, Whip, Mocha </li></ul></ul></ul><ul><li>MyCafe has decided to add sizes to these beverages. The cost varies based upon size. </li></ul>
  77. 77. Day 3 Agenda <ul><li>Bridge Pattern </li></ul><ul><li>Flyweight Pattern </li></ul><ul><li>Proxy Pattern </li></ul><ul><li>Structural Patterns Summary </li></ul><ul><li>Behavioral Patterns </li></ul><ul><ul><li>Command Pattern </li></ul></ul><ul><ul><li>Iterator Pattern </li></ul></ul>
  78. 78. Bridge Pattern <ul><li>Decouple an abstraction from its implementation so that the two can vary independently. </li></ul><ul><li>Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy. </li></ul><ul><li>Example </li></ul><ul><ul><li>Widgets on Different Platforms </li></ul></ul>
  79. 79. Bridge Pattern Thread Scheduler Priority Thread Scheduler WindowsTSTS UnixTSTS TimeSliced Thread Scheduler WindowsPTS UnixPTS Thread Scheduler Priority Thread Scheduler WindowsTSTS UnixTSTS TimeSliced Thread Scheduler WindowsPTS UnixPTS JavaPTS JavaTSTS
  80. 80. Bridge Pattern <ul><li>Decoupling interface and implementation </li></ul><ul><li>Improved extensibility </li></ul><ul><li>Hiding implementation details from clients </li></ul>Thread Scheduler Priority Thread Scheduler Windows TimeSliced Thread Scheduler Unix ThreadSchedulerImpl Java
  81. 81. Bridge Pattern – Implementation <ul><li>Only one implementer </li></ul><ul><li>Creating the right implementer object. How, when, and where </li></ul><ul><ul><li>Parameterized Implementation </li></ul></ul><ul><ul><li>Implementation based on conditions </li></ul></ul><ul><ul><li>Default Implementation </li></ul></ul>
  82. 82. Abstract Factory & Bridge AbstractWindowFactory Unix Window WindowImpl TransitWindow IconWindow
  83. 83. Class Problem <ul><ul><li>A company manufactures remote alarms for different types of Cars. The remotes could be for Alarm, door lock/unlock and Remote Car Start. Over a period of time, the company plans to come up with different designs for remote. The Car manufacturers could also come up with new models of Car. A remote should not be dependent on the Car. Create a UML based class diagram for this requirement. </li></ul></ul>
  84. 84. Bridge Pattern - Sample AlarmRemote Car DoorLock_Unlock Honda Remote RemoteStarter Toyota
  85. 85. Flyweight Pattern <ul><li>One instance of a class can be used to provide many “virtual instances” </li></ul><ul><li>Flyweight </li></ul><ul><ul><li>A shared object that can be used in multiple contexts simultaneously </li></ul></ul><ul><ul><li>Acts as an independent object in each context </li></ul></ul><ul><li>Make distinction between intrinsic and extrinsic state </li></ul><ul><ul><li>Intrinsic state is stored in flyweight </li></ul></ul><ul><ul><li>Extrinsic state varies with context and hence can be shared </li></ul></ul><ul><li>Example </li></ul><ul><ul><li>Characters in documents </li></ul></ul><ul><ul><ul><li>Properties – Coordinates, character code, typographic style </li></ul></ul></ul>
  86. 86. Flyweight Pattern - Example Your Code HeavyObject 1 HeavyObject 2 HeavyObject 3 HeavyObject 4
  87. 87. Flyweight Pattern - Example Your Code Configuration 1 Configuration 2 Configuration 3 Configuration 4 Flyweight Object
  88. 88. Flyweight Pattern - Applicability <ul><li>Apply when all of the following are true </li></ul><ul><ul><li>An application uses a large number of objects. </li></ul></ul><ul><ul><li>Storage costs are high because of the sheer quantity of objects. </li></ul></ul><ul><ul><li>Most object state can be made extrinsic. </li></ul></ul><ul><ul><li>Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed. </li></ul></ul><ul><ul><li>The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects. </li></ul></ul>
  89. 89. Flyweight Pattern - Structure FlyweightFactory GetFlyweight(key) Flyweight Operation(extrinsicState) ConcreteFlyweight Operation(extrinsicState) UnsharedConcreteFlyweight Operation(extrinsicState) Client IntrinsicState allState
  90. 90. Flyweight Pattern <ul><li>Consequences </li></ul><ul><ul><li>Introduce run-time costs of managing extrinsic state </li></ul></ul><ul><ul><ul><li>Transferring </li></ul></ul></ul><ul><ul><ul><li>Finding </li></ul></ul></ul><ul><ul><ul><li>Computing </li></ul></ul></ul><ul><ul><li>Extracting another generic template of extrinsic state. </li></ul></ul><ul><ul><ul><li>Could make the maintenance harder </li></ul></ul></ul><ul><li>Implementation </li></ul><ul><ul><li>Removing Extrinsic State </li></ul></ul><ul><ul><li>Managing shared objects </li></ul></ul>
  91. 91. Flyweight Pattern - Sample Student TestFlyWeight
  92. 92. Proxy Pattern <ul><li>Provide a surrogate or placeholder for another object to control access to it. </li></ul><ul><li>Use an extra level of indirection to support distributed, controlled, or intelligent access. </li></ul><ul><li>Add a wrapper and delegation to protect the real component from undue complexity. </li></ul><ul><li>Example </li></ul><ul><ul><li>Image Icon display </li></ul></ul>
  93. 93. Proxy Pattern – Types of Proxy <ul><li>Remote Proxy </li></ul><ul><ul><li>Hide the fact that an object resides in a different address space </li></ul></ul><ul><li>Virtual Proxy </li></ul><ul><ul><li>Perform optimizations such as creating an object on demand </li></ul></ul><ul><li>Protection Proxy </li></ul>
  94. 94. Proxy Pattern Subject Request() RealSubject Request() Proxy Request() realSubject Client
  95. 95. Proxy Variants Client Real Subject Proxy Remote Proxy Client Real Subject Proxy Virtual Proxy
  96. 96. Class Problem <ul><ul><li>An application has to communicate with weighing machines located in different geographies in public places. These machines should return the current status of number of remaining tickets inside them. Create a UML based class diagram for this requirement. </li></ul></ul>
  97. 97. Proxy Pattern - Sample State WeighingMachineClient WeighingMachineImpl WeighingMachineRemote
  98. 98. Adapter versus Proxy <ul><li>Adapter provides a different interface to the object it adapts </li></ul><ul><li>Proxy provides the same interface as its subject </li></ul><ul><ul><li>Proxies interface may be effectively a subset of the subjects </li></ul></ul>
  99. 99. Adapter versus Bridge <ul><li>Both promote flexibility </li></ul><ul><ul><li>Providing a level of indirection to another object </li></ul></ul><ul><ul><li>Involve forwarding requests to this object from an interface other than its own </li></ul></ul><ul><li>Adapter focuses on revolving incompatibilities between two existing interfaces </li></ul><ul><ul><li>Does not focus on how those interfaces are implemented </li></ul></ul><ul><ul><li>Way of making two independently designed classes work together without implementing one or the other </li></ul></ul><ul><li>Bridge </li></ul><ul><ul><li>Bridges an abstraction and its potential implementations. </li></ul></ul><ul><ul><li>Provides stable interface to clients </li></ul></ul><ul><ul><li>Accomodates new implementations as system evolves </li></ul></ul>
  100. 100. Composite versus Decorator versus Proxy <ul><li>Decorator </li></ul><ul><ul><li>Designed to let you add responsibilities to objects without sub-classing </li></ul></ul><ul><li>Composite </li></ul><ul><ul><li>Focuses on structuring classes so that many related objects can be treated uniformly </li></ul></ul><ul><li>Proxy and Decorator differ in their intent </li></ul><ul><ul><li>Proxy pattern is not concerned with attaching or detaching properties dynamically </li></ul></ul><ul><ul><li>Decorator addresses the functionality where total functionality cannot be determined at compile-time </li></ul></ul>
  101. 101. Behavioral Pattern
  102. 102. Command Pattern <ul><li>Encapsulate a request as an object </li></ul><ul><ul><li>Decouple object from requestor </li></ul></ul><ul><li>Parameterize clients with different requests </li></ul><ul><li>Support undoable operations </li></ul>Application Add(Document) Menu Add(Document) Document Open() Close() Cut() Copy() MenuItem Clicked() Command Execute()
  103. 103. Command Pattern - Example Document Open() Close() Cut() Copy() Command Execute() PasteCommand Execute() document
  104. 104. Command Pattern - Example Add(document) Application Command Execute() OpenCommand Execute() application
  105. 105. Command Pattern - Example Command Execute() MacroCommand Execute()
  106. 106. Command Pattern - Applicability <ul><li>Specify, queue and execute requests at different times </li></ul><ul><li>Support Undo </li></ul><ul><li>Support Logging Changes </li></ul>
  107. 107. Command Pattern - Structure Client Invoker Command Execute() Receiver Action() ConcreteCommand Execute() state receiver
  108. 108. Command Pattern - Example Command Manager AsiaServer Europe Server US Server
  109. 109. Command Pattern - Implementation <ul><li>Intelligent Commands </li></ul><ul><li>Supporting Undo/Redo </li></ul>
  110. 110. Undo/Redo Logic using Command Pattern
  111. 111. Class Problem <ul><li>A home automation company needs to build a Remote control to which home devices can be attached for automation. These devices could be – Outdoor Light, Ceiling Fan, Ceiling Fan, GardenLight, TV, Stereo, Thermostat, etc. The remote control could support upto 10 devices. For each device, on & off buttons are provided. Create a UML based class diagram for this requirement </li></ul>
  112. 112. Command Pattern - Sample Command GarageDoor GarageDoorOpenCommand Light LightOffCommand LightOnCommand RemoteControlTest SimpleRemoteControl
  113. 113. Iterator Pattern <ul><li>Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. </li></ul><ul><li>The C++ and Java standard library abstraction that makes it possible to decouple collection classes and algorithms. </li></ul><ul><li>Polymorphic traversal </li></ul>
  114. 114. Iterator Pattern AbstractList Client Iterator createIterator() Add(item) Remove(item) … List SkipList ListIterator SkipListIterator First() next() isDone() currentItem()
  115. 115. Iterator Pattern Client AbstractList Iterator createIterator() Add(item) Remove(item) … ConcreteAggregate ConcreteIterator First() next() isDone() currentItem() createIterator()
  116. 116. Iterator Pattern - Implementation <ul><li>Who controls the iterator ? </li></ul><ul><li>Who defines the traversal algorithm ? </li></ul><ul><li>How robust is the iterator ? </li></ul><ul><li>Null Iterator !! </li></ul>
  117. 117. Class Problem <ul><ul><li>A newly opened restaurant wants to create a new menu. There are menus for breakfast, lunch & dinner. Each menu has sub-categories such as sub-menu for pancakes in breakfast, sub-menu for chicken and vegetable dishes in lunch & dinner and a sub-menu for desserts. Any menu can be extended further with more categories. The menu should also support an iterator which could print the whole menu. Create a UML based design for this requirement. </li></ul></ul>
  118. 118. Iterator Sample Client CompositeIterator Menu MenuComponent MenuItem NullIterator
  119. 119. Problem of the Day <ul><li>A home automation company needs to build a Remote control to which home devices can be attached for automation. These devices could be – Outdoor Light, Ceiling Fan, Ceiling Fan, Garden Light, TV, Stereo, Thermostat, etc. The remote control could support upto 10 devices. For each device, on & off buttons are provided. The home automation company needs to provide a single undo button for the last command which was issued. I.e. if the light off button was pressed last, then the undo button would switch it on, etc. Create a UML based class diagram for this requirement. </li></ul>
  120. 120. Day 4 Agenda <ul><li>Chain of Responsibility </li></ul><ul><li>Observer </li></ul><ul><li>State </li></ul><ul><li>Strategy </li></ul><ul><li>Template Method </li></ul>
  121. 121. Chain of Responsibility Pattern <ul><li>Avoid coupling of the sender of a request to its receiver </li></ul><ul><li>Chain the receiving objects and pass the request along the chain until an object handles it </li></ul>printButton handler okButton printDialog application saveDialog handler handler handler handler
  122. 122. Chain of Responsibility Client Handler handleRequest ConcreteHandler1 handleRequest ConcreteHandler2 handleRequest successor
  123. 123. Chain of Responsibility <ul><li>Reduced Coupling </li></ul><ul><ul><li>Pattern frees an object from knowing which other object handles a request </li></ul></ul><ul><li>Added flexibility in assigning responsibilities to objects </li></ul><ul><ul><li>Flexibility in distributing responsibilities </li></ul></ul><ul><ul><li>Add or change responsibilities for handling a request </li></ul></ul><ul><li>Receipt isn’t guaranteed </li></ul><ul><ul><li>Request can go unhandled </li></ul></ul>
  124. 124. Chain of Responsibility - Implementation <ul><li>Implementing the successor chain </li></ul><ul><li>Connecting Successors </li></ul>
  125. 125. Class Problem <ul><li>The remote controls designed by the home automation company became an instant hit in the market. The company has been flooded with emails from fans, complaints, spam and new ideas. It wants to handle all these emails in an effective way such that mail detector can determine if an email is spam mail, fan mail, complaint or a new idea. Design a mail detector for this company. Give a UML based class diagram. </li></ul>
  126. 126. Chain of Responsibility - Sample MailHandler SpamHandler FanHandler
  127. 127. Observer Pattern <ul><li>Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. </li></ul><ul><li>Encapsulate the core components in a Subject abstraction, and the variable components in an Observer hierarchy. </li></ul><ul><li>Example </li></ul><ul><ul><li>Weather Station </li></ul></ul>
  128. 128. Observer Pattern - Structure Subject Attach(Observer) Detach(Observer) Notify() Observer Update() ConcreteSubject GetState() SetState() ConcreteObserver Update() observers subject
  129. 129. Observer Pattern - Consequences <ul><li>Abstract Coupling between Subject & Observer </li></ul><ul><li>Support for broadcast communication </li></ul><ul><li>Unexpected updates </li></ul>
  130. 130. Observer Pattern - Implementation <ul><li>Mapping subjects to their observers </li></ul><ul><li>Observing more than one subject </li></ul><ul><li>Who triggers the update ? </li></ul><ul><li>Subject should be self consistent before notification </li></ul><ul><li>Avoiding observer-specific update protocols </li></ul><ul><li>Encapsulating complex update semantics </li></ul>
  131. 131. Observer Pattern – Java implementation <ul><li>Flaws </li></ul><ul><ul><li>Observable is a class (violates OO principles) </li></ul></ul><ul><ul><li>There is no observable interface </li></ul></ul><ul><li>Observable protects crucial methods </li></ul><ul><ul><li>To use them, sub-classing is mandatory </li></ul></ul>
  132. 132. Observer Pattern - Sample CurrentConditionsDisplay StatisticsDisplay WeatherData ForecastDisplay Subject DisplayElement Observer WeatherStation HeatIndexDisplay
  133. 133. State Pattern <ul><li>Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. </li></ul><ul><li>An object-oriented state machine </li></ul>
  134. 134. Implementing State Machines <ul><li>Gather States (Threads) </li></ul><ul><ul><li>START, WORKING, SUSPENDED, STOP </li></ul></ul><ul><li>Create an instance variable to hold the current state </li></ul><ul><li>Gather actions which will cause the state transition </li></ul><ul><li>Write conditional code in each action class based on states. </li></ul>START WORKING SUSPENDED STOP
  135. 135. Implementing State Machine <ul><li>Addition of a new state would cause more conditions to be added to the methods. </li></ul><ul><li>Code does not adhere to </li></ul><ul><ul><li>Open Closed Principle </li></ul></ul><ul><ul><li>Encapsulation </li></ul></ul><ul><ul><li>Further additions could cause bugs </li></ul></ul>START WORKING SUSPENDED STOP New State
  136. 136. Refine Implementation <ul><li>Define a State interface containing methods for each action </li></ul><ul><li>Map each state directly to a class </li></ul>State Start Suspend Stop Working
  137. 137. State Pattern - Example TCPConnection Open() Close() Acknowledge() TCPState Open() Close() Acknowledge() TCPEstablished Open() Close() Acknowledge() TCPListen Open() Close() Acknowledge() TCPClosed Open() Close() Acknowledge() state
  138. 138. State Pattern - Structure Context State Handle() ConcreteStateA ConcreteStateB Handle() state
  139. 139. State Pattern - Consequences <ul><li>It localizes state-specific behavior and partitions behavior for different states </li></ul><ul><li>It makes state transitions explicit </li></ul><ul><li>State Object can be shared </li></ul><ul><li>Clients do not interact with the states directly </li></ul><ul><li>States can be shared if there are too many contexts ( Use Flyweight ) </li></ul>
  140. 140. Class Problem <ul><li>Consider a Toffee dispensing Machine with the following states – </li></ul><ul><li>WaitingForCoin – When the machine is idle, </li></ul><ul><li>HasCoin – When a coin is inserted into the machine, SoldState – When the dispense button is pressed </li></ul><ul><li>SoldOutState – When no toffees are left in the machine </li></ul><ul><li>Design a UML based class diagram for this requirement </li></ul>
  141. 141. State Pattern - Implementation NoCoin HasCoin SoldOut ToffeeMachine SoldState State
  142. 142. Strategy Pattern <ul><li>Defining a family of algorithms and making them interchangeable </li></ul><ul><li>Define algorithms and vary them independently from clients that use it </li></ul><ul><li>Capture the abstraction in an interface, bury implementation details in derived classes </li></ul>
  143. 143. Strategy Pattern - Example CacheReplacementPolicy removeItems() ReplacementPolicy remove() ReplacementPolicy remove() ReplacementPolicy remove() policy
  144. 144. Strategy Pattern - Applicability <ul><li>Many related classes differ only in their behavior </li></ul><ul><li>You need different variants of an algorithm </li></ul><ul><li>A class defines many behaviors, and these appear as multiple conditional statements </li></ul>
  145. 145. Strategy Pattern - Structure Context ContextInterface Strategy AlgorithmInterface() ConcreteStrategyA AlgorithmInterface() ConcreteStrategyB AlgorithmInterface() strategy
  146. 146. Strategy Pattern - Consequences <ul><li>Families of related algorithms </li></ul><ul><li>An alternative to sub-classing </li></ul><ul><li>Eliminate conditional statements </li></ul><ul><li>A choice of implementations </li></ul>
  147. 147. Strategy & State Pattern <ul><li>Very similar but different intent </li></ul><ul><li>State Pattern </li></ul><ul><ul><li>Built around discreet states </li></ul></ul><ul><ul><li>Context objects change state over time according to a state transition </li></ul></ul><ul><li>Strategy </li></ul><ul><ul><li>Control the strategy objects should be using </li></ul></ul>
  148. 148. Strategy Pattern - Implementation Car GoAlgorithm GoByDrivingAlgorithm GoByFlyingAlgorithm Helicopter Vehicle
  149. 149. Strategy & Decorator aDecorator component aDecorator component aComponent Decorator-extended functionality aComponent strategy aStrategy next aStrategy next Strategy-extended functionality
  150. 150. Template Method Pattern <ul><li>Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. </li></ul><ul><li>Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. </li></ul><ul><li>Base class declares algorithm ‘placeholders’ or ‘hooks’, and derived classes implement the placeholders. </li></ul>
  151. 151. Template Method Pattern - Structure AbstractClass TemplateMethod() PrimitiveMethod1() PrimitiveMethod2() ConcreteClass PrimitiveMethod1() PrimitiveMethod2()
  152. 152. Template Method Pattern - Consequences <ul><li>Fundamental technique for code reuse </li></ul><ul><li>Use ‘abstract methods’ when subclasses MUST provide an implementation </li></ul><ul><li>Use ‘hooks’ when a part of the algorithm is optional </li></ul><ul><li>How many abstract methods to provide </li></ul><ul><ul><li>Less granular, Less flexibility </li></ul></ul><ul><ul><li>More granular, more flexibility </li></ul></ul><ul><li>Follows the Hollywood principle ‘technique’ </li></ul>
  153. 153. Real world Templates <ul><li>Sorting Arrays </li></ul><ul><ul><li>Implement Comparable interface </li></ul></ul><ul><li>Java.io </li></ul><ul><ul><li>read(byte[],int,int) method in InputStream </li></ul></ul><ul><li>Jframe </li></ul><ul><ul><li>paint() method ( A hook ) can be overriden by custom frames </li></ul></ul><ul><li>Applet </li></ul><ul><ul><li>init(),start(),stop(),destroy(),paint() </li></ul></ul>
  154. 154. Template Method Pattern - Implementation CoffeeRobot Robot
  155. 155. Template Method & Strategy <ul><li>Strategy </li></ul><ul><ul><li>The class implements the entire algorithm </li></ul></ul><ul><ul><li>Defines a family of interchangeable algorithms </li></ul></ul><ul><ul><li>Uses delegation </li></ul></ul><ul><li>Templates </li></ul><ul><ul><li>Subclasses implement the missing parts of an algorithm </li></ul></ul><ul><ul><li>Can have different algorithms, but keeps control of the algorithm structure </li></ul></ul><ul><ul><li>Uses inheritance </li></ul></ul><ul><ul><li>Perfect for creating frameworks ( by providing hooks ) </li></ul></ul>
  156. 156. Problem of the Day <ul><li>Alarming systems Ltd. builds burglar alarms for home/commercial/vehicle, etc use. When an alarm is raised, the alarm system has to perform a series of steps. It has to produce an annoying sound, lock all the doors/windows, inform the police, inform the owners and optionally inform the neighbors. Create a UML design for this requirement. </li></ul>
  157. 157. Day 5 <ul><li>Mediator </li></ul><ul><li>Memento </li></ul><ul><li>Visitor </li></ul><ul><li>Interpreter </li></ul><ul><li>Summary </li></ul><ul><li>Compound Patterns </li></ul><ul><li>Other Patterns </li></ul>
  158. 158. Mediator Pattern <ul><li>Define an object that encapsulates how a set of objects interact. </li></ul><ul><li>Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. </li></ul><ul><li>Design an intermediary to decouple many peers. </li></ul>
  159. 159. Mediator Pattern - Example aFontDialogDirector Client director button director listBox director entryField director
  160. 160. Mediator Pattern Mediator Colleague ConcreteMediator ConcreteColleague2 ConcreteColleague1 mediator
  161. 161. Mediator Pattern - Implementation <ul><li>Omitting the abstract Mediator class </li></ul><ul><li>Colleague-Mediator Communication </li></ul><ul><ul><li>Implement Mediator as Observer pattern </li></ul></ul><ul><ul><ul><li>Mediator propagates changes to other colleagues </li></ul></ul></ul>
  162. 162. Mediator Pattern - Consequences <ul><li>Limits Sub-classing </li></ul><ul><ul><li>Localizes Behavior </li></ul></ul><ul><li>Decouples colleagues </li></ul><ul><li>Simplifies object protocols </li></ul><ul><ul><li>Replaces Many-to-many with one-to-many </li></ul></ul><ul><li>Abstracts how objects cooperate </li></ul><ul><li>Centralizes control </li></ul>
  163. 163. Mediator Pattern - Sample Welcome Mediator Purchase Page GoodBye Order
  164. 164. Mediator & Facade <ul><li>Mediator </li></ul><ul><ul><li>Arbitrary communication between colleague objects </li></ul></ul><ul><ul><li>Colleagues communicate with mediator instead of between themselves </li></ul></ul><ul><ul><li>Centralizes functionality that does not belong to any one of them </li></ul></ul><ul><li>Façade </li></ul><ul><ul><li>Interface to subsystem </li></ul></ul><ul><ul><li>Does not define a new functionality </li></ul></ul><ul><ul><li>Subsystem classes don’t know about the Facade </li></ul></ul>
  165. 165. Memento Pattern <ul><li>Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later. </li></ul><ul><li>A magic cookie that encapsulates a “check point” capability. </li></ul><ul><li>Promote undo or rollback to full object status. </li></ul><ul><li>Example – Saving state of a Game </li></ul>
  166. 166. Memento - Structure Originator SetMemento(Memento m) CreateMemento() state Memento GetState() state CareTaker memento
  167. 167. Memento - Applicability <ul><li>A snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later </li></ul><ul><li>A direct interface to obtaining the state would expose implementation details and break the object's encapsulation. </li></ul>
  168. 168. Memento Pattern - Consequences <ul><li>Preserving encapsulation boundaries </li></ul><ul><li>Simplifies Originator </li></ul><ul><li>May be expensive </li></ul><ul><li>Hidden costs in maintaining mementos </li></ul>
  169. 169. Memento Pattern - Sample CareTaker Memento Originator MementoExample
  170. 170. Command & Memento & Iterator <ul><li>Command can use memento to store state required for undo operation </li></ul><ul><ul><li>Store incremental changes </li></ul></ul><ul><li>An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally. </li></ul>
  171. 171. Visitor Pattern <ul><li>Represent an operation to be performed on the elements of an object structure. </li></ul><ul><li>Visitor lets you define a new operation without changing the classes of the elements on which it operates. </li></ul>
  172. 172. Visitor Pattern - Example Node TypeCode() GenerateCode() PrettyPrint() flowAnalysis() VariableNode TypeCode() GenerateCode() PrettyPrint() flowAnalysis() AssignmentNode TypeCode() GenerateCode() PrettyPrint() flowAnalysis()
  173. 173. Visitor Pattern - Example NodeVisitor VisitAssignment(AssignmentNode) VisitVariable(VariableNode) TypeCheckingNodeVisitor VisitAssignment(AssignmentNode) VisitVariable(VariableNode) CodeGeneratingNodeVisitor VisitAssignment(AssignmentNode) VisitVariable(VariableNode) Node Accept(NodeVisitor) VariableNode AssignmentNode Accept(NodeVisitor) Accept(NodeVisitor)
  174. 174. Visitor Pattern - Structure NodeVisitor VisitAssignment(AssignmentNode) VisitVariable(VariableNode) TypeCheckingNodeVisitor VisitAssignment(AssignmentNode) VisitVariable(VariableNode) CodeGeneratingNodeVisitor VisitAssignment(AssignmentNode) VisitVariable(VariableNode) Element Accept(NodeVisitor) ConcreteElementA ConcreteElementB Accept(NodeVisitor) Accept(NodeVisitor) Client ObjectStructure
  175. 175. Visitor Pattern - Consequences <ul><li>Makes adding new operations easy </li></ul><ul><li>Gathers related operations and separates unrelated ones </li></ul><ul><li>Adding new concrete element classes is hard </li></ul><ul><li>Visiting across class hierarchies </li></ul><ul><li>Accumulating state </li></ul><ul><li>Breaking Encapsulation </li></ul>
  176. 176. Visitor Pattern – Implementation <ul><li>Double Dispatch </li></ul><ul><li>Traversing the object structure </li></ul>
  177. 177. Class Problem <ul><li>Three brothers, “This”, “That” & “The Other” live in duplex house. At any time, they all must stay on the same floor. To move from one floor to the other, they need help and can be moved one by one. Create a UML based class diagram for this problem. </li></ul>
  178. 178. Visitor Pattern - Sample DownVisitor Element That TheOther This UpVisitor Visitor VisitorDemo
  179. 179. Interpreter Pattern <ul><li>Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. </li></ul><ul><li>Use it to build an interpreter for a language </li></ul>
  180. 180. Interpreter Pattern - Example <ul><li>expression ::= literal | alternation | sequence | repetition | '(' expression ')' </li></ul><ul><li>alternation ::= expression '|' expression </li></ul><ul><li>sequence ::= expression '&' expression </li></ul><ul><li>repetition ::= expression '*' </li></ul><ul><li>literal ::= 'a' | 'b' | 'c' | ... { 'a' | 'b' | 'c' | ... }* </li></ul>
  181. 181. Interpreter Pattern - Example RegularExpression Interpret() SequenceExpression Interpret() LiteralExpression Interpret() AlternateExpression Interpret() RepetitionExpression Interpret() literal
  182. 182. Interpreter Pattern - Applicability <ul><li>The grammar is simple </li></ul><ul><ul><li>If grammar is very complex use tools such as parser generators </li></ul></ul><ul><li>Efficiency is not a critical concern </li></ul><ul><ul><li>Efficient interpreters are not implemented by interpreting parse trees directly </li></ul></ul><ul><ul><li>Regular expressions are often transformed into state machine </li></ul></ul>
  183. 183. Interpreter Pattern - Structure AbstractExpression Interpret(Context) TerminalExpression Interpret(Context) NonTerminalExpression Interpret(Context) Client Context
  184. 184. Interpreter Pattern - Consequences <ul><li>Easy to change and extend the grammar </li></ul><ul><li>Implementing the grammar is easy </li></ul><ul><li>Complex grammar is hard to maintain </li></ul><ul><li>Adding new ways to interpret expressions </li></ul>
  185. 185. Interpreter Pattern - Implementation <ul><li>Creating the abstract syntax tree </li></ul><ul><li>Defining the interpret operation </li></ul><ul><ul><li>Defining interpret() method is not mandatory </li></ul></ul><ul><ul><li>Consider use of Visitor pattern </li></ul></ul><ul><li>Sharing terminal symbols with Flyweight </li></ul>
  186. 186. Interpreter Pattern - Sample Expression Interpreter2 InterpreterDemo Number Operand Variable
  187. 187. Multiple patterns at work - Problem <ul><li>We have a fleet of motor vehicles and would like to drive them </li></ul><ul><li>We would like to add Helicopters into this fleet </li></ul><ul><li>We would like to record their mileage </li></ul><ul><li>We forgot to add drive record decorator </li></ul><ul><li>Its difficult to manage all these cars and helicopters Some are in groups, some alone. Need to manage. </li></ul><ul><li>Notify us when any car/helicopters drives itself </li></ul>
  188. 188. Model-View-Controller <ul><li>Model </li></ul><ul><ul><li>Holds the data, state and application logic </li></ul></ul><ul><li>View </li></ul><ul><ul><li>Gives a representation of the model </li></ul></ul><ul><li>Controller </li></ul><ul><ul><li>Takes user input and routes it appropriately </li></ul></ul>
  189. 189. MVC with patterns <ul><li>Observer </li></ul><ul><ul><li>Whenever the model changes, controller and view get notified. Ex. Stock Prices </li></ul></ul><ul><li>Strategy </li></ul><ul><ul><li>View is the context and delegates any calls to the controller </li></ul></ul><ul><ul><li>View knows nothing about how this gets done </li></ul></ul><ul><li>Composite </li></ul><ul><ul><li>View is a nested set of components – Window(Composite), button(leaf) </li></ul></ul>
  190. 190. Antipatterns <ul><li>Patterns that tell you how to avoid bad solutions </li></ul><ul><ul><li>Example: Golden Hammer </li></ul></ul>
  191. 191. Summary <ul><li>Encapsulation </li></ul><ul><li>Program to an interface, not to an implementation </li></ul><ul><li>Safety vs Transparency </li></ul>
  192. 192. Thankyou