Java Design Patterns By Gaurav Tyagi
Day 1 - Agenda UML & Design Principles Introduction to Java Design Patterns Creational Patterns Singleton Factory Method Prototype Abstract Factory
UML – Elements Class Attributes Operations Relationships IS-A Inheritance HAS-A Composition/Aggregation
Design Principles Encapsulation Separate what varies from what stays the same Program to an interface, not an implementation Remember Polymorphism ?? Favor Object composition over Class Inheritance Delegation Strive for loosely couples designs between objects that interact
Design Principles – Open-Closed Principle New changes should be added with minimum changes to the existing code Intent Classes should be open for extension and closed for modification Should be applied to those areas which are likely to change Do not apply to every area of the system
Design Principle – Open-Closed Principle 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; } }
Design Principle – Open Closed Principle class GraphicEditor { public void drawShape(Shape s) { s.draw(); } } class Shape { abstract void draw(); } class Rectangle extends Shape { public void draw() { // draw the rectangle } }
Design Principle – Dependency Inversion Depend upon abstractions  Do not depend on concrete classes High level components should NOT depend upon low level components Write code so that we depend upon abstractions High Level Classes --> Abstraction Layer --> Low Level Classes
Design Principle – Dependency Inversion 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 } }
Design Principle – Dependency Inversion 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(); } }
Design Principle – Interface Segregation Clients should not be forced to implement interfaces that they don’t use Instead of one fat interface, create many small interfaces If design is already done with fat interfaces – use adapter pattern
Design Principle – Principle of least knowledge Talk only to your immediate friends For any object, limit the number of classes it interacts with Prevents changes from cascading to other parts of the system We should only invoke methods that belong to The object itself Objects passed in as parameter to the method Any object that method creates or instantiates Any components of the object
Design Principle - Single Responsibility A class should have only one reason to change More than one responsibility implies more than one area of change Cohesion High Cohesion: Classes or modules designed around a set of related functions Low Cohesion: Classes or modules designed around a set of unrelated functions Classes that adhere to the principle tend to have high cohesion
Don’t Repeat yourself (DRY) One Requirement in one place Each piece of information and behavior in a single sensible place
Liskov Substitution Principle (LSP) Subtypes must be substitutable for their base types
What are Design Patterns ? Design Pattern "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” Class Patterns Deal with relationships between classes and their sub-classes Static and established at compile time Object Patterns Deal with object relationships which are more dynamic and can change at runtime
Which pattern to use ? Creating an object by specifying a class explicitly Dependence on specific operations Dependence on hardware and software platform Dependence on object representations or implementations Algorithmic dependencies Tight Coupling Extending functionality by sub-classing Inability to alter classes conveniently
Types of Java Pattern Creational Patterns Concern with the process of Object Creation Class Patterns Defer some part of object creation to subclasses Object Patterns Defer creation to another object Structural Patterns Deal with composition of classes or objects Class Patterns Use inheritance to compose classes Object Patterns Describe ways to assemble objects
Types of Java Patterns Behavioral Patterns Concerned with algorithms and the assignment of responsibilites between objects Class Patterns Use inheritance to describe algorithms and flow of control Object Patterns Describe how a group of objects cooperate to perform a task that no single object can carry out alone
Creational Patterns
Singleton Pattern Important for some classes to have exactly one instance Ex: For many printers, there should be only one printer spooler Make a class itself responsible for keeping track of its sole instance Structure Singleton static Instance() Singleton Operation() GetSingletonData() static uniqueInstance singletonData return uniqueInstance
Singleton Pattern  Pros/Cons Controlled access to sole instance Reduced Name space Implementation Ensuring a unique instance final class RemoteConnection {  private Connect con;  private static RemoteConnection rc = new  RemoteConnection(connection);  private RemoteConnection(Connect c) { con = c; .... }  public static RemoteConnection getRemoteConnection() { return rc; }  public void setConnection(Connect c) {  this(c);  }  }
Singleton in a Distributed Environment Singleton is one instance per virtual machine/class loader A singleton cannot be shared across multiple JVMs.
Singleton Pattern – Sample Singleton ThreadSafe Singleton Classic Singleton Preferred
Factory Method To be used when it must be decided at runtime which one of the several compatible classes is to be instantiated Instantiation in public can lead to coupling problems All products implement the same interface Abstract Class Client class Concrete class Product Product Class
Factory Method Advantage Provides hooks for subclasses Connects parallel class hierarchies Disadvantage Clients have to subclass the creator class just to create a particular concrete product object Avoid subclass with templates Figure TextFigure Linefigure Client Manipulator Text Manipulator Line Manipulator
Factory Method - Implementation Parameterized Factory Methods Factory takes a parameter as input Creates multiple kinds of products Creator class is abstract and provides no implementation for the factory method Creator is a concrete class and provides a default implementation of the factory
Class Problem 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.
Factory Method – Sample Code Toy Bus Cycle SimpleToyFactory Car ToyStore Scooter
Prototype Specifying the kind of objects to create using a Prototypical instance and creating objects using this prototype When the classes to instantiate are specified at runtime To avoid building a class hierarchy of factories that parallels the class hierarchy of products Should be considered when system needs to create new objects of many types in a complex class hierarchy
Prototype - Structure Client Prototype clone() ConcretePrototype1 clone() ConcretePrototype2 clone()
Prototype Advantages of Cloning(Prototype) over Subclassing(Factory) Factory Method: Creation through inheritance Prototype: Creation through delegation Providing a "create based on existing state" 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. Benefits & Drawbacks Shallow Copy Deep Copy Adding and Removing Products at runtime Specifying new objects by varying value Reduced Subclasses
Prototype Pattern Variants Copy Constructor public class Prototype {  private int someData; // some more data  public Prototype(Prototype original) {  super();  this.someData = original.someData;  //copy the rest of the data  } // rest of code  } Clone method Prototype manager Registry for prototypes when the number of prototypes isn’t fixed
Prototype - Sample Bus Car Cycle Scooter SimpleToyFactory Toy ToyStore
Abstract Factory Pattern Motivation Different look and feel define different appearances and behavior Applicability System should be independent of how its products are created, composed and represented System should be configured with one of multiple families of products A family of related product objects is designed to be used together  Provide a class of library of products and only expose their interfaces, not their implementations
Abstract Factory Pattern - Structure CreateProductA() CreateProductB() AbstractFactory createProductA() createProductB() ConcreteFactory1 createProductA() createProductB() ConcreteFactory2 Client AbstractProductA AbstractProductB ProductA1 ProductA2 ProductB1 ProductB2
Abstract Factory Pattern Pros/Cons Isolates concrete Classes Makes exchanging product Families easy Promotes consistency among products Supporting new kind of products is difficult Implementation Factories as Singletons Product Creation Factory Method  for each product Requires a new factory for each product family For mulitple product families, use  Prototype  pattern. Eliminates the need for a new concrete factory class for each product family
Exercise 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.
Abstract Factory Pattern – Sample Code PlasticDoor Accelerator Door PlasticAccelerator PlasticSeat PlasticToyFactory Seat ToyPartsFactory WoodenAccelerator WoodenDoor WoodenSeat WoodenToyFactory
Problem of the Day 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.
Day 2 Agenda Builder Pattern Creational Patterns - Summary Overview of Structural Patterns Adapter  Facade Bridge Composite
Builder Pattern Intent Separate the construction of a complex object from its representation so that the same construction process can create different representations. Parse a complex representation, create one of several targets. Applicability The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled The construction process must allow different representations for the object that's constructed
Builder Pattern - Structure Director Builder ConcreteBuilder builder Construct() BuildPart() BuildPart() GetResult()
Builder Pattern - Consequences Lets you vary a products internal representation Isolates code for construction and representation Gives you finer control over construction process
Class Problem  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
Builder Pattern - Implementation Builder Day Vacation VacationBuilder
Rules of Thumb Builder & Abstract Factory Common Interface Abstract Factory might store a set of Prototypes from which to clone and return product objects.  Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
Creational Patterns - Summary Factory Method: creation through inheritance. Protoype: creation through delegation. Prototype doesn’t require sub-classing, but it does require an “initialize” operation. Factory Method requires sub-classing, but doesn’t require Initialize. Prototype is unique among the other creational patterns in that it doesn’t require a class – only an object.
Strutural Patterns
Adapter Pattern Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. Interface an old component to a new system Need to use several existing subclasses Example AC Power adapter
Adapter Pattern Vendor System Adapter Existing Class Vendor System Existing Class
Adapter Pattern - Structure Class Adapter   Using  Inheritance Object Adapter Using Delegation Client Target Adaptee Adapter Request() specificReq() Request() Call specificReq() Client Target Request() Adaptee specificReq() Adapter Request() Call  adaptee->specificReq()
Adapter Pattern Trade-offs between class and object adapters Class Adapter Adapts Adaptee to Target by committing to a concrete Adapter class Lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of Adaptee. Introduces only one object, and no additional pointer indirection is needed to get to the adaptee Object Adapter Lets a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses Makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter
Adapter Pattern – Pluggable Adapters They are classes with built-in interface adaptation Example: TreeDisplay widget Implementation approaches Using abstract Operations 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) }
Adapter Pattern – Pluggable Adapters Using delegate objects 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
Adapter Pattern How much adapting to do ? Does an adapter always wrap one and only one class ?
Class Problem Adapt an Enumeration to an Iterator Enumeration Interface hasMoreElements() nextElement() Iterator hasNext() Next() Remove()
Adapter Pattern - Sample Bombay Duck Client Duck Turkey Turkey WildTurkey
Facade Pattern 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. Wrap a complicated subsystem with a simpler interface. Example Home Theatre, Compiler
Facade Pattern Facade
Façade Pattern - Benefits Decouples clients from subsystem components Clients only code to facade Promotes weak coupling between the subsystem and its clients Doesn’t encapsulate sub-system. Only provides a simpler interface The subsystem is still accessible for direct use
Façade Patterns - Implementation Can facade add its own functionality ? Number of facades Façade and adapters may wrap multiple classes, but the difference is in their intent Façade simplifies an interface Adapter converts the target interface into something that client is expecting
Façade Pattern - Sample Projector Amplifier CdPlayer DvdPlayer HomeTheatreFacade HomeTheatreClient PopcornPopper Tuner Screen TheatreLights
Decorator Pattern Attach/Detach additional responsibilities to an object dynamically.  Provide a flexible alternative to sub-classing for extending functionality. Wrapping a gift, putting it in a box, and wrapping the box. New behavior is acquired by composition and NOT by subclassing
Decorator Pattern Component Concrete Component Decorator Component Decorator ComponentB Decorator ComponentA component
Decorator Pattern More flexibility than static inheritance Lots of little objects Implementation Interface Conformance Keeping component classes light weight
Real world Decorator Java.io package is largely based on decorator FileInputStream Decorated by BufferedInputStream Decorated by LineNumberInputStream
Class Problem 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) Beverages: HouseBlend, Espresso, DarkRoast, Decaf Condiments: Milk, Soy, Whip, Mocha
Decorator Pattern - Sample Beverage CondimentDecorator DarkRoast Decaf Espresso HouseBlend Milk Mocha Soy StarbucksCoffee Whip
Composite Pattern Compose objects into tree structures to represent part-whole hierarchies Recursive composition Picture Text Rectangle Line Rectangle Line Picture
Composite Pattern Client Component doThis() Leaf Composite doThis() Add(Component) Remove(Component) GetChild(Int) children doThis()
Composite Pattern - Consequences Defines class hierarchies consisting of primitive components and composite components Clients can treat individual & composite object uniformly Makes it easier to add new kind of components
Composite Pattern - Implementation Maintaining references from child components to their parent Sharing components Maximizing the Component interface Declaring the child management operations
Class Problem 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.
Composite Pattern - Sample Menu MenuComponent MenuItem MenuTestClient
Problem of the day 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 Beverages: HouseBlend, Espresso, DarkRoast, Decaf Condiments: Milk, Soy, Whip, Mocha MyCafe has decided to add sizes to these beverages.  The cost varies based upon size.
Day 3 Agenda Bridge Pattern Flyweight Pattern Proxy Pattern Structural Patterns Summary Behavioral Patterns Command Pattern Iterator Pattern
Bridge Pattern Decouple an abstraction from its implementation so that the two can vary independently. Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy. Example Widgets on Different Platforms
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
Bridge Pattern Decoupling interface and implementation Improved extensibility Hiding implementation details from clients Thread Scheduler Priority Thread Scheduler Windows TimeSliced Thread Scheduler Unix ThreadSchedulerImpl Java
Bridge Pattern – Implementation Only one implementer Creating the right implementer object. How, when, and where Parameterized Implementation Implementation based on conditions Default Implementation
Abstract Factory & Bridge AbstractWindowFactory Unix Window WindowImpl TransitWindow IconWindow
Class Problem 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.
Bridge Pattern - Sample AlarmRemote Car DoorLock_Unlock Honda Remote RemoteStarter Toyota
Flyweight Pattern One instance of a class can be used to provide many “virtual instances” Flyweight  A shared object that can be used in multiple contexts simultaneously Acts as an independent object in each context Make distinction between intrinsic and extrinsic state Intrinsic state is stored in flyweight Extrinsic state varies with context and hence can be shared Example Characters in documents Properties – Coordinates, character code, typographic style
Flyweight Pattern - Example Your Code HeavyObject 1 HeavyObject 2 HeavyObject 3 HeavyObject 4
Flyweight Pattern - Example Your Code Configuration 1 Configuration 2 Configuration 3 Configuration 4 Flyweight Object
Flyweight Pattern - Applicability Apply when  all  of the following are true An application uses a large number of objects. Storage costs are high because of the sheer quantity of objects. Most object state can be made extrinsic. Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed. The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.
Flyweight Pattern - Structure FlyweightFactory GetFlyweight(key) Flyweight Operation(extrinsicState) ConcreteFlyweight Operation(extrinsicState) UnsharedConcreteFlyweight Operation(extrinsicState) Client IntrinsicState allState
Flyweight Pattern Consequences Introduce run-time costs of managing extrinsic state Transferring  Finding Computing Extracting another generic template of extrinsic state. Could make the maintenance harder Implementation Removing Extrinsic State Managing shared objects
Flyweight Pattern - Sample Student TestFlyWeight
Proxy Pattern Provide a surrogate or placeholder for another object to control access to it.  Use an extra level of indirection to support distributed, controlled, or intelligent access. Add a wrapper and delegation to protect the real component from undue complexity. Example Image Icon display
Proxy Pattern – Types of Proxy Remote Proxy Hide the fact that an object resides in a different address space Virtual Proxy Perform optimizations such as creating an object on demand Protection Proxy
Proxy Pattern Subject Request() RealSubject Request() Proxy Request() realSubject Client
Proxy Variants Client Real Subject Proxy Remote Proxy Client Real Subject Proxy Virtual Proxy
Class Problem 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.
Proxy Pattern - Sample State WeighingMachineClient WeighingMachineImpl WeighingMachineRemote
Adapter versus Proxy Adapter provides a different interface to the object it adapts Proxy provides the same interface as its subject Proxies interface may be effectively a subset of the subjects
Adapter versus Bridge Both promote flexibility Providing a level of indirection to another object Involve forwarding requests to this object from an interface other than its own Adapter focuses on revolving incompatibilities between two existing interfaces Does not focus on how those interfaces are implemented Way of making two independently designed classes work together without implementing one or the other Bridge Bridges an abstraction and its potential implementations.  Provides stable interface to clients  Accomodates new implementations as system evolves
Composite versus Decorator versus Proxy Decorator Designed to let you add responsibilities to objects without sub-classing Composite Focuses on structuring classes so that many related objects can be treated uniformly Proxy and Decorator differ in their intent Proxy pattern is not concerned with attaching or detaching properties dynamically Decorator addresses the functionality where total functionality cannot be determined at compile-time
Behavioral Pattern
Command Pattern Encapsulate a request as an object Decouple object from requestor Parameterize clients with different requests Support undoable operations Application Add(Document) Menu Add(Document) Document Open() Close() Cut() Copy() MenuItem Clicked() Command Execute()
Command Pattern - Example Document Open() Close() Cut() Copy() Command Execute() PasteCommand Execute() document
Command Pattern - Example Add(document) Application Command Execute() OpenCommand Execute() application
Command Pattern - Example Command Execute() MacroCommand Execute()
Command Pattern - Applicability Specify, queue and execute requests at different times Support Undo Support Logging Changes
Command Pattern - Structure Client Invoker Command Execute() Receiver Action() ConcreteCommand Execute() state receiver
Command Pattern - Example Command Manager AsiaServer Europe Server US Server
Command Pattern - Implementation Intelligent Commands Supporting Undo/Redo
Undo/Redo Logic using Command Pattern
Class Problem 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
Command Pattern - Sample Command GarageDoor GarageDoorOpenCommand Light LightOffCommand LightOnCommand RemoteControlTest SimpleRemoteControl
Iterator Pattern Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. The C++ and Java standard library abstraction that makes it possible to decouple collection classes and algorithms. Polymorphic traversal
Iterator Pattern AbstractList Client Iterator createIterator() Add(item) Remove(item) … List SkipList ListIterator SkipListIterator First() next() isDone() currentItem()
Iterator Pattern Client AbstractList Iterator createIterator() Add(item) Remove(item) … ConcreteAggregate ConcreteIterator First() next() isDone() currentItem() createIterator()
Iterator Pattern - Implementation Who controls the iterator ? Who defines the traversal algorithm ? How robust is the iterator ? Null Iterator !!
Class Problem 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.
Iterator  Sample Client CompositeIterator Menu MenuComponent MenuItem NullIterator
Problem of the Day 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.
Day 4 Agenda Chain of Responsibility Observer State Strategy Template Method
Chain of Responsibility Pattern Avoid coupling of the sender of a request to its receiver Chain the receiving objects and pass the request along the chain until an object handles it printButton handler okButton printDialog application saveDialog handler handler handler handler
Chain of Responsibility Client Handler handleRequest ConcreteHandler1 handleRequest ConcreteHandler2 handleRequest successor
Chain of Responsibility Reduced Coupling Pattern frees an object from knowing which other object handles a request Added flexibility in assigning responsibilities to objects Flexibility in distributing responsibilities Add or change responsibilities for handling a request Receipt isn’t guaranteed Request can go unhandled
Chain of Responsibility - Implementation Implementing the successor chain Connecting Successors
Class Problem 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.
Chain of Responsibility - Sample MailHandler SpamHandler FanHandler
Observer Pattern Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Encapsulate the core components in a Subject abstraction, and the variable components in an Observer hierarchy. Example Weather Station
Observer Pattern - Structure Subject Attach(Observer) Detach(Observer) Notify() Observer Update() ConcreteSubject GetState() SetState() ConcreteObserver Update() observers subject
Observer Pattern - Consequences Abstract Coupling between Subject & Observer Support for broadcast communication Unexpected updates
Observer Pattern - Implementation Mapping subjects to their observers Observing more than one subject Who triggers the update ? Subject should be self consistent before notification Avoiding observer-specific update protocols Encapsulating complex update semantics
Observer Pattern – Java implementation Flaws Observable is a class (violates OO principles) There is no observable interface Observable protects crucial methods To use them, sub-classing is mandatory
Observer Pattern - Sample CurrentConditionsDisplay StatisticsDisplay WeatherData ForecastDisplay Subject DisplayElement Observer WeatherStation HeatIndexDisplay
State Pattern Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. An object-oriented state machine
Implementing State Machines Gather States (Threads) START, WORKING, SUSPENDED, STOP Create an instance variable to hold the current state Gather actions which will cause the state transition Write conditional code in each action class based on states. START WORKING SUSPENDED STOP
Implementing State Machine Addition of a new state would cause more conditions to be added to the methods. Code does not adhere to Open Closed Principle Encapsulation Further additions could cause bugs START WORKING SUSPENDED STOP New State
Refine Implementation Define a State interface containing methods for each action Map each state directly to a class State Start Suspend Stop Working
State Pattern - Example TCPConnection Open() Close() Acknowledge() TCPState Open() Close() Acknowledge() TCPEstablished Open() Close() Acknowledge() TCPListen Open() Close() Acknowledge() TCPClosed Open() Close() Acknowledge() state
State Pattern - Structure Context State Handle() ConcreteStateA ConcreteStateB Handle() state
State Pattern - Consequences It localizes state-specific behavior and partitions behavior for different states It makes state transitions explicit State Object can be shared Clients do not interact with the states directly States can be shared if there are too many contexts ( Use Flyweight )
Class Problem Consider a Toffee dispensing Machine with the following states –  WaitingForCoin – When the machine is idle,  HasCoin – When a coin is inserted into the machine, SoldState – When the dispense button is pressed SoldOutState – When no toffees are left in the machine Design a UML based class diagram for this requirement
State Pattern - Implementation NoCoin HasCoin SoldOut ToffeeMachine SoldState State
Strategy Pattern Defining a family of algorithms and making them interchangeable Define algorithms and vary them independently from clients that use it Capture the abstraction in an interface, bury implementation details in derived classes
Strategy Pattern - Example CacheReplacementPolicy removeItems() ReplacementPolicy remove() ReplacementPolicy remove() ReplacementPolicy remove() policy
Strategy Pattern - Applicability Many related classes differ only in their behavior You need different variants of an algorithm A class defines many behaviors, and these appear as multiple conditional statements
Strategy Pattern - Structure Context ContextInterface Strategy AlgorithmInterface() ConcreteStrategyA AlgorithmInterface() ConcreteStrategyB AlgorithmInterface() strategy
Strategy Pattern - Consequences Families of related algorithms An alternative to sub-classing Eliminate conditional statements A choice of implementations
Strategy & State Pattern Very similar but different intent State Pattern Built around discreet states Context objects change state over time according to a state transition Strategy Control the strategy objects should be using
Strategy Pattern - Implementation Car GoAlgorithm GoByDrivingAlgorithm GoByFlyingAlgorithm Helicopter Vehicle
Strategy & Decorator aDecorator component aDecorator component aComponent Decorator-extended functionality aComponent strategy aStrategy next aStrategy next Strategy-extended functionality
Template Method Pattern Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.  Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. Base class declares algorithm ‘placeholders’ or ‘hooks’, and derived classes implement the placeholders.
Template Method Pattern - Structure AbstractClass TemplateMethod() PrimitiveMethod1() PrimitiveMethod2() ConcreteClass PrimitiveMethod1() PrimitiveMethod2()
Template Method Pattern - Consequences Fundamental technique for code reuse Use ‘abstract methods’ when subclasses MUST provide an implementation Use ‘hooks’ when a part of the algorithm is optional How many abstract methods to provide Less granular, Less flexibility More granular, more flexibility Follows the Hollywood principle ‘technique’
Real world Templates Sorting Arrays Implement Comparable interface Java.io read(byte[],int,int) method in InputStream Jframe paint() method ( A hook ) can be overriden by custom frames Applet init(),start(),stop(),destroy(),paint()
Template Method Pattern - Implementation CoffeeRobot Robot
Template Method & Strategy Strategy   The class implements the entire algorithm Defines a family of interchangeable algorithms Uses delegation Templates Subclasses implement the missing parts of an algorithm Can have different algorithms, but keeps control of the algorithm structure Uses inheritance Perfect for creating frameworks ( by providing hooks )
Problem of the Day 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.
Day 5 Mediator Memento Visitor Interpreter Summary Compound Patterns Other Patterns
Mediator Pattern Define an object that encapsulates how a set of objects interact.  Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. Design an intermediary to decouple many peers.
Mediator Pattern - Example aFontDialogDirector Client director button director listBox director entryField director
Mediator Pattern Mediator Colleague ConcreteMediator ConcreteColleague2 ConcreteColleague1 mediator
Mediator Pattern - Implementation Omitting the abstract Mediator class Colleague-Mediator Communication Implement Mediator as Observer pattern Mediator propagates changes to other colleagues
Mediator Pattern - Consequences Limits Sub-classing Localizes Behavior Decouples colleagues Simplifies object protocols Replaces Many-to-many with one-to-many Abstracts how objects cooperate Centralizes control
Mediator Pattern - Sample Welcome Mediator Purchase Page GoodBye Order
Mediator & Facade Mediator Arbitrary communication between colleague objects Colleagues communicate with mediator instead of between themselves Centralizes functionality that does not belong to any one of them Façade Interface to subsystem  Does not define a new functionality Subsystem classes don’t know about the Facade
Memento Pattern Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later. A magic cookie that encapsulates a “check point” capability. Promote undo or rollback to full object status. Example – Saving state of a Game
Memento - Structure Originator SetMemento(Memento m) CreateMemento() state Memento GetState() state CareTaker memento
Memento - Applicability A snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later  A direct interface to obtaining the state would expose implementation details and break the object's encapsulation.
Memento Pattern - Consequences Preserving encapsulation boundaries Simplifies Originator May be expensive Hidden costs in maintaining mementos
Memento Pattern - Sample CareTaker Memento Originator MementoExample
Command & Memento & Iterator Command can use memento to store state required for undo operation Store incremental changes An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.
Visitor Pattern Represent an operation to be performed on the elements of an object structure.  Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Visitor Pattern - Example Node TypeCode() GenerateCode() PrettyPrint() flowAnalysis() VariableNode TypeCode() GenerateCode() PrettyPrint() flowAnalysis() AssignmentNode TypeCode() GenerateCode() PrettyPrint() flowAnalysis()
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)
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
Visitor Pattern - Consequences Makes adding new operations easy Gathers related operations and separates unrelated ones Adding new concrete element classes is hard Visiting across class hierarchies Accumulating state Breaking Encapsulation
Visitor Pattern – Implementation Double Dispatch Traversing the object structure
Class Problem 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.
Visitor Pattern - Sample DownVisitor Element That TheOther This UpVisitor Visitor VisitorDemo
Interpreter Pattern Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Use it to build an interpreter for a language
Interpreter Pattern - Example expression ::= literal | alternation | sequence | repetition | '(' expression ')' alternation ::= expression '|' expression sequence ::= expression '&' expression repetition ::= expression '*' literal ::= 'a' | 'b' | 'c' | ... { 'a' | 'b' | 'c' | ... }*
Interpreter Pattern - Example RegularExpression Interpret() SequenceExpression Interpret() LiteralExpression Interpret() AlternateExpression Interpret() RepetitionExpression Interpret() literal
Interpreter Pattern - Applicability The grammar is simple If grammar is very complex use tools such as parser generators Efficiency is not a critical concern Efficient interpreters are not implemented by interpreting parse trees directly Regular expressions are often transformed into state machine
Interpreter Pattern - Structure AbstractExpression Interpret(Context) TerminalExpression Interpret(Context) NonTerminalExpression Interpret(Context) Client Context
Interpreter Pattern - Consequences Easy to change and extend the grammar Implementing the grammar is easy Complex grammar is hard to maintain Adding new ways to interpret expressions
Interpreter Pattern - Implementation Creating the abstract syntax tree Defining the interpret operation Defining interpret() method is not mandatory Consider use of Visitor pattern  Sharing terminal symbols with Flyweight
Interpreter Pattern - Sample Expression Interpreter2 InterpreterDemo Number Operand Variable
Multiple patterns at work - Problem We have a fleet of motor vehicles and would like to drive them We would like to add Helicopters into this fleet We would like to record their mileage We forgot to add drive record decorator Its difficult to manage all these cars and helicopters Some are in groups, some alone. Need to manage. Notify us when any car/helicopters drives itself
Model-View-Controller Model Holds the data, state and application logic View Gives a representation of the model Controller Takes user input and routes it appropriately
MVC with patterns Observer Whenever the model changes, controller and view get notified. Ex. Stock Prices Strategy View is the context and delegates any calls to the controller View knows nothing about how this gets done Composite View is a nested set of components – Window(Composite), button(leaf)
Antipatterns Patterns that tell you how to avoid bad solutions Example: Golden Hammer
Summary Encapsulation Program to an interface, not to an implementation Safety vs Transparency
Thankyou

P Training Presentation

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