team 4 design patterns n.
Skip this Video
Download Presentation

Loading in 2 Seconds...

play fullscreen
1 / 179

TEAM 4: DESIGN PATTERNS - PowerPoint PPT Presentation

  • Uploaded on

TEAM 4: DESIGN PATTERNS. BY Piyush Vijayvargiya Young Jin Kim Bimesh Giri Arkadiy Gorelik SPRING 2003, COMP 680. Introduction . What is a PATTERN?.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'TEAM 4: DESIGN PATTERNS' - lada

Download Now An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
team 4 design patterns


Piyush Vijayvargiya

Young Jin Kim

Bimesh Giri

Arkadiy Gorelik

SPRING 2003, COMP 680

what is a pattern
What is a PATTERN?
  • A description of a solution to a recurring problem within a context, proven by experience to lead to a superior result when properly applied.
  • A design pattern is a description of communicating objects and classes that are customized to solve a general design problem in a particular context
why a design pattern
Why a Design Pattern
  • Reusability: For an efficient and actual SE discipline.
  • Helping new designers to have a more flexible and reusable design.
  • Improving the documentation and maintenance of existing system by furnishing an explicit specification of class and object interactions and their intent.
history of design pattern
History of Design Pattern
  • 1979:Christopher Alexander,architect, “The Timeless Way of Building”,Oxford Press.
  • 1987:OOPSLA (Object Oriented Programming System),Orlando, presentation of design pattern to the community OO by Ward Cunningham and Kent Beck.
  • 1995:Group of Four alias E.Gamma, R.Helm,R.Johnson and J.Vlissides : “Design Pattern:Elements of Reusable OO software”.
pattern characteristics
Pattern Characteristics
  • Each pattern has a name.
  • Patterns follow a loosely standardized document format, generally employing a conversational tone.
  • They may also include diagrams, pictures or source code to help the reader understand the pattern.
  • Additionally, each pattern provides suggestions of other possible patterns to consider instead of, or in conjunction with that particular pattern to help solve larger problems.
  • Thus patterns are literary form of Problem Solving.
essential qualities of a true pattern
Essential Qualities of a True Pattern.
  • Quality Without a Name (QWaN): Fundamentally, QWaN means that, when applied correctly to solve an applicable problem, the resulting solution provides a structure that can evolve over time to meet unanticipated future needs.
essential qualities cont
Essential Qualities Cont.
  • Rule of Three :
  • In order for a solution to really be a 'pattern', there must already exist known uses of the solution, with results that can be observed.
  • This rule states that, for any solution to be a true pattern, there must be at least three known instances of that solution.
essential qualities cont1
Essential Qualities Cont.
  • Pattern Format:
  • Patterns are documented following a loosely standardized format.
  • FORMAT: The structure of any solution presented as a pattern may be informal or formal. Minimally, each pattern must specify a name, the purpose of the pattern, a description of the solution and the forces it resolves. Additional sections may be included as well.
pattern formats
Pattern Formats
  • A pattern may be very brief - consisting of only a few paragraphs of conversational text - or it may be documented in many pages of a book or published paper.
  • A pattern may be very loosely or strictly structured. For software design patterns, a more strict structure is usually preferred, with each pattern divided into a number of topic sections.
common pattern sections
Common pattern sections
  • Name
  • Problem or Intent
  • Context or Applicability
  • Solution
  • Forces or Consequences
  • Related Patterns
  • Known Uses
name of design pattern
Name of Design Pattern
  • Have to be coherent and evocative.
  • Describe a design problems and its solutions in one or two sentences.
  • Used to talk about design pattern with the colleagues.
  • Used in the documentation.
problem or intent
Problem or Intent
  • Describes when to apply the patterns.
  • Explains the problem and its context.
  • Sometimes include a list of conditions that must be met before it makes sense to apply the pattern.
  • Have to occur over and over again in our environment.
context or applicability
Context or Applicability
  • This is the section which tells that when the particular pattern can be applied and what is the problem in a particular context that can be solved using the particular pattern.
  • Describes the elements that make up the design, their relationships, responsibilities and collaborations.
  • Does not describe a concrete design or implementation.
  • Has to be well proven in some projects.
forces or consequences
Forces or Consequences
  • Results and trade-offs of applying the pattern.
  • Helpful for describe design decisions, for evaluating design alternatives.
  • Benefits of applying a pattern.
  • Impacts on a system’s flexibility, extensibility or portability
related patterns
Related Patterns
  • This section mentions the names of the other known patterns which are related to this pattern and are used to get to the solution of the problem encountered in the particular context .
  • Or it can be give the names of the pattern which are almost the same and can be used as substitute patterns.
known uses
Known Uses
  • As we have already seen that in order for a pattern to be a true pattern there should be at least three independent instances of the solution provided by the pattern.
  • So this section list some of the known uses of the pattern.
classification of design patterns
Classification of Design Patterns
  • The design Patterns may be Classifies as
  • Creational Design Patterns.
  • Structural Design Patterns.
  • Behavioral Design Patterns.
  • Concept of creational design pattern.
  • Understanding of 5 different creational design patterns with code examples.
  • The right usage of creational design patterns.
  • Giving an idea of how to create object using Design pattern to apply your own application.
what is creational design pattern
What is creational Design pattern?
  • About how an object can be created.






Return object


what is creational design pattern cont
What is creational Design pattern? (cont)
  • Design patterns that abstracts the object instantiation process.
  • help system be independent of how its objects are created, composed, and represented
  • Client application just use object without know how it’s created.
what is creational design pattern cont1
What is creational Design pattern? (cont)
  • examples of object creation
  • JFrame myFrame=new JFrame(“Sky”);//new operator create object
  • Border blackline= BorderFactory.createLineBorder(;//calling method to get specific object from object Factory
  • JPanel drawingPanel= new JPanel();Graphics g= drwaingPanel.getGraphics();//Graphic object is created depending on panel object.
kinds of creational design pattern
Kinds of Creational Design pattern
  • The Factory Method.
  • The Abstract Factory Method
  • The Builder Pattern
  • The Prototype Pattern
  • The Singleton Pattern
kinds of creational design pattern brief introduction
Kinds of Creational Design pattern(brief introduction)
  • The Factory Method:defines an interface for creating an object, but let subclasses decide which class to instantiate.
  • The Abstract Factory Method:provides an interface for creating families of related or dependent objects without specifying their concrete classes.
kinds of creational design pattern brief introduction cont
Kinds of Creational Design pattern(brief introduction)(cont)
  • The Builder Patternseparates the construction of a complex object from its representation so that the same construction process can create different representations
  • The Prototype Patternspecifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
kinds of creational design pattern brief introduction cont1
Kinds of Creational Design pattern(brief introduction)(cont)
  • The Singleton Patternensures that a class only has one instance, and provide a global point of access to it.
the factory method concept
The Factory Method<concept>
  • defines an interface for creating an object, but let subclasses decide which class to instantiate.
  • returns an instance of one of several possible classes depending on the data provided to it.
  • common parent, methods but different performance and optimized for different data
  • is tools used for simplifying tangled programming classes.
the factory method concept cont
The Factory Method<concept > (cont)
  • Also Know as Virtual Constructor
  • structural Diagram
the factory method example cont

Sky Kimor

Kim, Sky

Name Factory

First Name: Sky

Last Name: Kim

The Factory Method<Example> (cont)

Input( First name comes first or last name comes first )

Factory analyze input and create right object and output.

Output(first/last names are separated)

the factory method example code cont
The Factory Method<Example: code> (cont)
  • Classes: super class: Namersub classes: FirstFirst, LastFirstFactory class: NameFactoryClient class: Driver
the factory method example code functional classes cont
The Factory Method<Example: code: Functional Classes>(cont)
  • class Namer {protected String first, last; //store first, last name herepublic String getFirst() { return first; } //return first namepublic String getLast() {return last; } //return last name


Sub class create proper object

class FirstFirst extends Namer { //split first last

public FirstFirst(String s) {

int i = s.lastIndexOf(" "); //find separating space

if (i > 0) {first = s.substring(0, i).trim();

last =s.substring(i+1).trim(); }

else {

first = “”; // put all in last name

last = s; // if no space


class LastFirst extends Namer { //split last, first

public LastFirst(String s) {

int i = s.indexOf(","); //find comma

if (i > 0) {last = s.substring(0, i).trim();

first = s.substring(i + 1).trim();}

else {

last = s; // put all in last name

first = ""; // if no comma


the factory method example code factory classes cont
The Factory Method<Example: code: Factory Classes>(cont)

//returns an instance of LastFirst or FirstFirstdepending on whether a comma is found

class NameFactory {

public Namer getNamer(String entry) {

int i = entry.indexOf(","); //comma determines name order

if (i>0)

return new LastFirst(entry); //return LastFirst object


return new FirstFirst(entry); // return FirstFirst object}}

the factory method example code driver classes cont
The Factory Method<Example: code: Driver Classes>(cont)

class Driver{

private void computeName() {

NameFactory nfactory=new NameFactory(); //create Factory.

//send the text to the factory and get a class back

namer = nfactory.getNamer(entryField.getText());

System.out.println(“First Name: “+namer.getFirst());

System.out.println(“Last Name: “+namer.getLast());


the factory method when to use
The Factory Method<When to use>
  • ·a class can’t anticipate which kind of class of objects it must create.
  • ·a class uses its subclasses to specify which objects it creates.
  • ·you want to localize the knowledge of which class gets created.
  • ·classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
the abstract factory method concept
The Abstract Factory Method<concept>
  • is one level higher abstraction than the Factory pattern.
  • is a factory object that returns one of several factories.
  • to provide an interface for creating families of related or dependent objects without specifying their concrete classes

The Abstract Factory Method<concept>

  • Use this pattern when you want to return one of several related classes of objects, each of which can return several different objects on request.
  • isolates the concrete classes that are generated and actual class names of these classes are hidden in the factory and need not be known at the client level at all.
  • may define all of the subclasses’ methods in the abstract class.
the abstract factory method example in java api
The Abstract Factory Method<Example in Java API>
  • Most language’s Look and Feel is done by this pattern.
  • .getSystemLookAndFeelClassName() method return proper LookAndFeel name. Various LookAndFeel classes are hidden encapsulated from Driver client class.

class Driver{ public Driver(){ String laf = UIManager.getSystemLookAndFeelClassName();

try { UIManager.setLookAndFeel(laf); }

catch (UnsupportedLookAndFeelException exc)

{System.err.println("UnsupportedL&F: " + laf);}

catch (Exception exc)

{System.err.println("Error loading " + laf);}


the abstract factory method example display print drivers
The Abstract Factory Method<Example: Display/Print Drivers>
  • A computer system displays and prints shapes depending on the CPU speed and the memory size of the computer.
  • Different Driver for different machines
the abstract factory method example display print drivers cont
The Abstract Factory Method<Example: Display/Print Drivers>(cont)
  • Class abstraction hierarchy for drivers
the abstract factory method example display print drivers cont1
The Abstract Factory Method<Example: Display/Print Drivers>(cont)
  • Middle level Machine may need High and Low resolution types
  • need class hierarchy regarding to High and Low resolution like following diagram
the abstract factory method example resfactory cont
The Abstract Factory Method<Example: ResFactory>(cont)
  • two class hierarchies under the same classes: we have two factory considerations.
  • need to retrieve proper drivers regarding to Print/Display with High and Low resolution for both drivers.
  • need a factory class returns object regarding 2 class hierarchies.
  • How to put these together?: Abstract Factory Pattern is a good solution.
the abstract factory method example resfactory cont1
The Abstract Factory Method<Example: ResFactory>(cont)
  • structure of classes with Abstract Factory pattern
the abstract factory method example resfactory code cont
The Abstract Factory Method<Example: ResFactory code>(cont)

abstract class ResFactory{

abstract public DisplayDriver getDispDrvr();

abstract public PrintDriver getPrtDrvr();} 

class LowResFact extends ResFactory{

public DisplayDriver getDispDrvr(){

return new LRDD(); }

public PrintDriver getPrtDrvr(){

return new LRPD();}

class HighResFact extends ResFactory{

public DisplayDriver getDispDrvr(){

return new HRDD(); }

public PrintDriver getPrtDrvr(){

return new HRPD();}


the abstract factory method when to use
The Abstract Factory Method<When to use>
  • The client object does not know which particular concrete implementations of the server objects it has because the factory object has the responsibility to create them.
  • The client object does not even know which particular factory it uses since it only knows that it has an Abstract Factory object. It has concrete factory classes implementing it, but it doesn’t know which one to use.
the builder pattern concept
The Builder Pattern<Concept>
  • is used to separate the construction of a complex object from its representation so that the same construction process can create different representations.
  • The pattern assembles a number of objects to make a new (Abstract) Factory Pattern return existing object without assembling objects.
  • The (Abstract) Factory Pattern returns factory made productwhile the Builder pattern returns custom made product.
the builder pattern concept structure diagram
The Builder Pattern<Concept: structure diagram>
  • Client request to Director
  • one abstract builder with several ConcreteBuilders
  • Director decides which builder will be used to build a result.
the builder pattern example house building
The Builder Pattern<Example: House Building>
  • You have a choice to choose your home between an Apartment without backyard and a single-family home with backyard.
  • Depends on whether you want a backyard or not Director will call proper house object with its description that will be return to the user
  • Essential classes needed:

Client, Director, House(abstract), Apt(type of house), SFH(type of house)

the builder pattern use it when
The Builder Pattern<Use it when..>
  • 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.
the prototype pattern concept
The Prototype Pattern<Concept>
  • is used to specify the kinds of objects, called Prototype, to create using a prototypical instance, and create new objects by copying this prototype.
  • When creating an instance of a class is very time-consuming or complex in some way, you make copies of the original instance and modifying them as appropriate rather than creating more instances
the prototype pattern concept class structure
The Prototype Pattern<Concept: class structure>
  • Prototype is the object type that Client wants
  • Prototype (abstract) has several Concrete sub types.
the prototype pattern how to clone
The Prototype Pattern<How to clone>
  • Shallow Clone(copy)copy any object references in the original object list.
  • Deep Clone(copy)copy any actual object themselves in the original object list.
the prototype pattern how to clone shallow copy
The Prototype Pattern<How to clone: Shallow copy>
  • Language API provides it.
  • Java: Object Object.clone()(object must implement Cloneable interface)
  • C#:


PrototypeObject proto;proto= (PrototypeObject) protoObject.clone();proto.performMethod();

the prototype pattern how to clone deep copy
The Prototype Pattern<How to clone: Deep copy>
  • implement with your own codeusing Byte Stream: Write object to byte stream and Read it back and return it as a copy.
  • Example of Deep Clone

public Object deepClone() {

try{ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(b); out.writeObject(this);ByteArrayInputStream bIn = new ByteArrayInputStream(b.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bIn);

return (oi.readObject()); }catch (Exception e){ e.printStackTrace(); return null;}}

the prototype pattern use it when
The Prototype Pattern<Use it when>
  • a system should be independent of how its products are created, composed, and represented.
  • classes to instantiate are specified at run-time, for example, by dynamic loading, or to avoid building a class hierarchy of factories that parallels the class hierarchy of products
  • instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.
the singleton pattern concept
The Singleton Pattern<Concept>
  • is used to ensure a class has one instance and provides global point of access to it.
  • make a class itself responsible for keeping track of its sole instance
  • The class can ensure that no other instance can be crated, and it can provide a way to access the instance.
the singleton pattern concept structure diagram
The Singleton Pattern<Concept: structure Diagram>
  • keep instance unique.
  • all client share the same object.
the singleton pattern example printer spooling
The Singleton Pattern<Example: Printer spooling>
  • Many computer use the same printer and the requests from computers are spooled by only one Spooler.
  • Spooler must be one instance that is shared by all computers.
the singleton pattern example printer spooler w different approach
The Singleton Pattern<Example: Printer spooler w/ different approach>
  • Throw Exception
  • return null

public class Spooler {

private static bool instance_flag= false;

private Spooler() {}

public static Spooler getSpooler() {

if (! instance_flag)

return new Spooler ();else

return null;


  • Spooler sp3 = new Spooler ();fails at compiler time since construct is privatized like System.Math class in C# or Java
conclusion of creational design pattern
Conclusion of Creational Design Pattern
  • All of the creational patterns deal with the best way to create instances of objects.
  • One problem left is when and how to use the proper creational pattern that can be applied to the design situation given.
  • Further work includes applying each pattern to the real-life design, which might entail many trials and errors.
structural patterns introduction
Structural Patterns: Introduction

• Often a single object can comprise many parts, or be an entry point into a network of related objects

• Structural Patterns address ways to compose

classes and objects to form larger structures

structural patterns adapter intent
Structural Patterns: ADAPTER: Intent
  • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
  • Target
    • defines the domain-specific interface that Client uses.
  • Client
    • collaborates with objects conforming the Target interface.
  • Adaptee
    • defines an existing interface that needs adapting.
  • Adapter
    • adapts the interface of Adaptee to the Target interface.
  • Adapter pattern is the only design pattern that can be done in both class-based way and object-based way.
  • A Class adapter uses multiple inheritance to adapt one interface to another. An object adapter relies on object composition. Class adapter uses a static relationship, which is fixed at the time of compiling. Object adapter handles more dynamic situations, which can be changed at run-time.
example adding a class to a package
Example – Adding a Class to a Package

• Suppose we have developed a set of classes that support a drawing package

• The base for all interfaces in the package is the Shape interface

• Our package describes the bounding box of a

shape in terms of its lower left and upper right


• We want to incorporate a newly purchased class,TextView.

• However, TextView describes its bounding box in terms of its origin (the lower left corner) and its extent (the height and width)

• Shape and TextView provide different interfaces for returning the bounding box information about a shape

• We want to create a new class, TextShape, which provides all the functionality of TextView through an interface that’s compatible with the Shape interface

  • you want to use an existing class, and its interface does not match the one you need.
  • you want to create a reusable class that cooperates with unrelated or unforeseen classes.
structural patterns bridge intent
Structural Patterns: BRIDGE: Intent

Decouple an abstraction from its implementation so that the two can vary independently.

  • Abstraction
    • defines the abstraction's interface.
  • Refined Abstraction
    • extends the interface defined by Abstraction.
  • Implementor
    • defines the interface for implementation classes.
  • ConcreteImplementor
    • implements the Implementor interface and defines its concrete implementation.
  • Bridge pattern decouples the abstraction from its implementation putting them in different class hierarchies.
  • Basically a class interface is separated from its implementation by making each a separate but tightly coupled object. The interface object forwards client request to the appropriate implementation object.
example encapsulating data access
Example – Encapsulating Data Access

• Most interesting problem domain objects have

state which is stored in external databases or files

• It is desirable to separate the functionality of the

problem domain object (e.g., Customer or

Account) from the services required to read/write

the object’s state from/to the external data source

example encapsulating data access 2
Example– Encapsulating Data Access – 2

• We want to define an interface that allows us to read/write data from several kinds of data sources.

• This will provide a bridge between the data management objects and disparate back-end systems.

  • Use the Bridge Pattern when you want to vary the implementation of an interface or set of interfaces at run-time, independently of the interface.
  • you want to avoid a permanent binding between an abstraction and its implementation.
  • both the abstractions and their implementations should be extensible by sub classing.
structural patterns composite intent
Structural Patterns: Composite: Intent
  • Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • Component
    • declares the interface for objects in the composition.
    • implements default behavior common to all classes.
  • Leaf
    • represents leaf objects in the composition.
    • defines behavior for primitive objects in the composition.
  • Composite
    • defines behavior for aggregate components having children.
    • stores child components.
  • Client
    • manipulates objects in the composition through the Component interface.
  • Composite classes extend a base class that represents primitive objects.
  • The Composite class maintains a collection of components.
The Fileable class maps to Component in the generic Composite Pattern. Directory maps to Composite, and File maps to the Leaf class.
  • Client code that wants to print a list of the Fileable items in a Directory can utilize the common data members name and permissions to build a line by line description.
  • Use the Composite Pattern when you have a whole-part hierarchy that has significant similarities among the things which are containers and the things which are not.
  • you want clients to be able to ignore the difference between compositions of objects and individual objects.
structural patterns decorator intent
Structural Patterns: DECORATOR: Intent

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

  • Component
    • defines the interface for objects that can have responsibilities added to them dynamically.
  • Concrete Component
    • define an object to which additional responsibilities can be attached.
  • Decorator
    • maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • Concrete Decorator
    • adds responsibilities to the component.
  • to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
  • for responsibilities that can be withdrawn.
  • when extension by subclassing is impractical.
structural patterns facade intent
Structural Patterns: FACADE: Intent

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.

  • Facade
    • provides a unified higher-level interface to the subsystem functionality.
    • knows which subsystem classes are responsible for a request.
    • delegates client requests to appropriate subsystem objects.
  • subsystem classes
    • implement subsystem functionality.
    • handle work assigned by the Facade object.
    • have no knowledge of the facade.
  • A façade class encapsulating the details of underlying complex subsystems.
  • The façade and the complex subsystems are placed in a separate package from the client.
  • The subsystems are made Private and the façade is made Public (or at least accessible to the client).
  • You want to provide a simple interface to a complex subsystem.
  • There are many dependencies between clients and the implementation classes of an abstraction.
  • You want to layer your subsystems.
structural patterns flyweight intent
Structural Patterns: FLYWEIGHT: Intent

Use sharing to support large number of fine-grained objects efficiently.

  • Flyweight
    • declares an interface through which flyweights can receive and act on extrinsic state.
  • ConcreteFlyweight
    • implements the Flyweight interface and adds storage for intrinsic state, if any.
  • UnsharedConcreteFlyweight
    • not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing, but does not enforce it.
    • creates and manages flyweight objects.
  • Client
    • maintains a reference to flyweight(s).
    • computes or stores the extrinsic state of flyweight(s).
example object oriented editor
Example – Object Oriented Editor
  • Using an object for each character in the document would promote flexibility at the finest levels in the application. But even moderate-sized documents may require hundreds of thousands of character objects, and thereby incur unacceptable memory space and run-time overhead.
  • The Flyweight pattern provides a way of sharing objects to allow their use at fine granularities without prohibitive cost.
  • 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.
structural patterns proxy intent
Structural Patterns: PROXY: Intent

Provide a surrogate or placeholder for another object to control access to it.

  • Proxy

maintains a reference that lets the proxy access the real subject.


defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.

  • RealSubject

defines the real object that the proxy represents.

  • The subject class is abstract defining interface.
  • The Realsubject is a subclass of the Subject which actually implements the subject interface.
  • Further Proxy is defined as the sub class of the Realsubject having same set of methods and similar interface.
example reference counting
Example – Reference Counting
  • Since there may be many places where clients can access the same Customer object, Reference count is employed to support memory management.
  • The reference counts are incremented and decremented through methods on the Customer object, say,incrementReferenceCount() and decrementReferenceCount()
  • A remote proxy provides a local representative for an object in a different address space.
  • A protection proxy control access to the original object.
behavioral patterns introduction
Behavioral Patterns: Introduction
  • Concerned with algorithms and the assignment of responsibilities between objects
  • Characterize complex control flow that is difficult to follow at run-time
behavioral patterns class patterns
Behavioral Patterns: ClassPatterns
  • Use inheritance to distribute behavior between classes
  • Relationships between classes are static
  • One class is an abstract definition of an algorithm and it defines the algorithm step by step, where each step invokes either abstract operation or a primitive operation
  • A subclass impelements an abstract algorithm
behavioral patterns object patterns
Behavioral Patterns: Object Patterns
  • Use object composition rather than inheritance
  • Relationships between classes are dynamic
  • Some describe how a group of peer objects cooperate to perform a task that no single object can carry out by itself
behavioral patterns chain of responsibility intent
Behavioral Patterns: Chain of Responsibility: Intent
  • Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request
  • Chain the receiving objects and pass the request along the chain until an object handles it
behavioral patterns chain of responsibility participants
Behavioral Patterns: Chain of Responsibility: Participants
  • Handler (HelpHandler) - defines an interface for handling requests and implements the successor link (optional)
  • ConcreteHandler (PrintButton, PrintDialog) - handles requests it is responsible for and can access its successor
  • Client - initiates the request to a ConcreteHandler object on the chain
behavioral patterns chain of responsibility structure
Behavioral Patterns: Chain of Responsibility: Structure
  • When a client issues a request, the request propagates along the chain until a ConcreteHandler object takes responsibility for handling it
behavioral patterns chain of responsibility applicability
Behavioral Patterns: Chain of Responsibility: Applicability
  • More than one object may handle a request, and the handler does not know the priority and is determined automatically
  • You want to issue a request to one of several objects without specifying the receiver explicitly
behavioral patterns chain of responsibility consequences
Behavioral Patterns: Chain of Responsibility: Consequences
  • Reduced Coupling – object only has to know that a request will be handled appropriately
  • Added flexibility in assigning responsibilities to objects – can add or change responsibilities for handling a request by changing the chain at run-time
  • Any candidate may fulfill the request depending on run-time conditions
  • The number of candidates is open-ended and can be selected in any order
behavioral patterns command intent
Behavioral Patterns: Command: Intent
  • Encapsulate a request as an object
  • Parameterize clients with different requests, queue or log requests, and support undoable operations
behavioral patterns command participants
Behavioral Patterns: Command: Participants
  • Command - declares an interface for executing an operation
  • ConcreteCommand - defines a binding between a Receiver object and an action
  • Client - creates a ConcreteCommand object and sets its receiver
  • Invoker - asks the command to carry out the request
  • Receiver - knows how to perform the operations associated with carrying out a request
behavioral patterns command structure
Behavioral Patterns: Command: Structure
  • The client creates a ConcreteCommand object, specifies receiver
  • An Invoker object stores the ConcreteCommand object
  • The invoker issues a request (Execute) on the command
  • The ConcreteCommand object invokes operation on its receiver to carry out the request
behavioral patterns command applicability
Behavioral Patterns: Command: Applicability
  • Parameterize objects by an action to perform (Commands are OO replacement for callbacks)
  • Specify, queue, and execute requests at different times
  • Support Undo (Unexecute operation)
behavioral patterns command consequences
Behavioral Patterns: Command: Consequences
  • Command decouples the object that invokes the operation from the one that knows how to perform it
  • Commands are first-class objects and can be extended and manipulated like any other object
  • It is easy to add new Command because you don’t have to change existing classes
  • It is easy to assemble commands into a composite command
behavioral patterns interpreter intent
Behavioral Patterns: Interpreter: Intent
  • Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language
behavioral patterns interpreter participants
Behavioral Patterns: Interpreter: Participants
  • AbstractExpression - declares an abstract Interpret operation that is common to all nodes in the abstract syntax tree
  • TerminalExpression - implements an Interpret operation associated with terminal symbols in the grammar
  • NonterminalExpression - required for every rule

R := R1R2R3…Rn in the grammar and implements an Interpret operation for nonterminal symbols in the grammar

  • Context - contains information that is global to the interpreter
  • Client - builds an abstract syntax tree representing a particular sentence and invokes the Interpret operation
behavioral patterns interpreter structure
Behavioral Patterns: Interpreter: Structure
  • Client builds sentence as ABSYNT of NTE and TE
  • Client initializes the context and invokes Interpret()
  • Interpret operations at each node use the context to store and access the state of the interpreter
behavioral patterns interpreter applicability
Behavioral Patterns: Interpreter: Applicability
  • When there is a language to interpret and the statements in the language can be represented as abstract syntax tree
  • Grammar has to be simple
behavioral patterns interpreter consequences
Behavioral Patterns: Interpreter: Consequences
  • It is easy to change and extend the grammar
  • Implementing the grammar is easy
  • Complex grammars are hard to maintain
  • Adding new ways to interpret expressions
behavioral patterns iterator intent
Behavioral Patterns: Iterator: Intent
  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation
behavioral patterns iterator participants
Behavioral Patterns: Iterator: Participants
  • Iterator - defines an interface for accessing and traversing elements
  • ConcreteIterator - implements the Iterator interface and keeps track of current position in the traversal of the aggregate
  • Aggregate - defines an interface for creating an Iterator object
  • ConcreteAggregate – implements the Iterator creation interface to return an instance of the proper ConcreteIterator
behavioral patterns iterator structure
Behavioral Patterns: Iterator: Structure
  • A ConcreteIterator keeps track of the current object in the aggregate and can compute the succeeding object in the traversal
behavioral patterns iterator applicability
Behavioral Patterns: Iterator: Applicability
  • To access an aggregate object’s contents without exposing its internal representation
  • To support multiple traversals of aggregate objects
  • To provide a uniform interface for traversing different aggregate structures (support polymorphic iteration)
behavioral patterns iterator consequences
Behavioral Patterns: Iterator: Consequences
  • It supports variations in the traversal of an aggregate
  • Complex aggregates may be traversed in many ways
  • More than one traversal can be pending on an aggregate
  • An iterator keeps track of its own traversal state allowing more than one traversal in progress at once
behavioral patterns mediator intent
Behavioral Patterns: Mediator: Intent
  • Define an object that encapsulates how a set of objects interact
  • Mediator promotes loose coupling by keeping objects from referring to each other explicitly
  • Mediator allows to vary object interaction independently
behavioral patterns mediator participants
Behavioral Patterns: Mediator: Participants
  • Mediator - defines an interface for communicating with Colleague objects
  • ConcreteMediator - implements cooperative behavior by coordinating Colleague objects and knows and maintains its colleagues
  • Colleague classes - each Colleague class knows its Mediator object and each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague
behavioral patterns mediator structure
Behavioral Patterns: Mediator: Structure
  • Colleagues send and receive requests from a Mediator object
  • The mediator implements the cooperative behavior by routing requests between the appropriate colleague(s)
behavioral patterns mediator applicability
Behavioral Patterns: Mediator: Applicability
  • A set of objects communicate in well-defined but complex ways
  • Reusing an object is difficult because it refers to and communicates with many objects
  • A behavior that is distributed between several classes should be customizable without a lot of subclassing
behavioral patterns mediator consequences
Behavioral Patterns: Mediator: Consequences
  • It limits subclassing
  • It decouples colleagues
  • It simplifies object protocols
  • It abstracts how objects cooperate
  • It centralizes control
behavioral patterns memento intent
Behavioral Patterns: Memento: Intent
  • Capture and externalize an object’s internal state so that the object can be restored to this state later without violating encapsulation
behavioral patterns memento participants
Behavioral Patterns: Memento: Participants
  • Memento - stores internal state of the Originator object and protects against access by objects other than the originator
  • Originator - creates a memento containing a snapshot of its current internal state and uses the memento to restore its internal state
  • Caretaker - responsible for memento’s safekeeping and never operates on or examines the contents of a memento
behavioral patterns memento structure
Behavioral Patterns: Memento: Structure
  • A caretaker requests a memento from an originator, holds it for some time, and passes it back to the originator if it is needed to revert to an earlier state
  • Mementos are passive. Only the originator that created a memento will assign or retrieve its state
behavioral patterns memento applicability
Behavioral Patterns: 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
behavioral patterns memento consequences
Behavioral Patterns: Memento: Consequences
  • Preserves encapsulation boundaries
  • Using mementos might be expensive
  • It may be difficult in some languages to ensure that only the originator can access the memento’s state
behavioral patterns observer intent
Behavioral Patterns: Observer: Intent
  • Define a one-to-many dependency between objects so that when one object changes state, all its dependencies are notified and updated automatically
behavioral patterns observer participants
Behavioral Patterns: Observer: Participants
  • Subject - knows its observers and provides an interface for attaching/detaching Observer objects
  • Observer - defines an updating interface for objects that should be notified of changes in a subject
  • ConcreteSubject - stores state of interest to ConcreteObserver objects and sends a notification to its observers when its state changes
  • ConcreteObserver - maintains a reference to a ConcreteSubject object and stores state that should stay consistent with the subject’s and implements the Observer updating interface to keep its state consistent with the subject’s
behavioral patterns observer structure
Behavioral Patterns: Observer: Structure
  • ConcreteSubject notifies its observers whenever a change occurs that could make its observer’s state inconsistent with its own
  • ConcreteObserver may query the subject for more information
behavioral patterns observer applicability
Behavioral Patterns: Observer: Applicability
  • When an abstraction has two aspects where one is dependent on the other
  • When a change to one object requires changing others, and the number of objects that need to be changed is unknown
  • When an object should be able to notify other objects without making assumptions about who these objects are
behavioral patterns observer consequences
Behavioral Patterns: Observer: Consequences
  • Abstract and minimal coupling between Subject and Observer
  • Support for broadcast communication. The notification from the sender is broadcast automatically to all interested objects that subscribed to it
  • Unexpected updates. Because observers have no knowledge of each other’s presence, they can be blind to the ultimate cost of changing the subject
behavioral patterns state intent
Behavioral Patterns: State: Intent
  • Allow an object to alter its behavior when its internal state changes
  • The object will appear to change its class
behavioral patterns state participants
Behavioral Patterns: State: Participants
  • Context (TCPConnection) - defines the interface of interest to clients and maintains an instance of a ConcreteState subclass that defines the current state
  • State (TCPState) - defines an interface for encapsulating the behavior associated with a particular state of Context
  • ConcreteState subclass (TCPEstablished, TCPListen, TCPClosed) - each subclass implements a behavior associated with a state of the Context
behavioral patterns state structure
Behavioral Patterns: State: Structure
  • Context delegates state-specific request to the current ConcreteState object
  • Context is the primary interface for clients
  • Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances
behavioral patterns state applicability
Behavioral Patterns: State: Applicability
  • An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state
  • Operations have large, multipart conditional statements that depend on the object’s state, so the State pattern puts each branch of the conditional in a separate class
behavioral patterns state consequences
Behavioral Patterns: State: Consequences
  • It localizes state-specific behavior and partitions behavior for different states. Puts all behavior associated with a particular state into one object
  • It makes state transitions explicit. Because introducing separate objects for different states makes the transitions more explicit
  • State objects can be shared
behavioral patterns strategy intent
Behavioral Patterns: Strategy: Intent
  • Define a family of algorithms, encapsulate each one, and make them interchangeable
  • Strategy lets the algorithm vary independently from clients that use it
behavioral patterns strategy participants
Behavioral Patterns: Strategy: Participants
  • Strategy - declares an interface common to all supported algorithms
  • ConcreteStrategy - implements the algorithm using the Strategy interface
  • Context - maintains a reference to a Strategy object, configured with a ConcreteStrategy object, and may define an interface that lets Strategy access its data
behavioral patterns strategy structure
Behavioral Patterns: Strategy: Structure
  • Strategy and Context interact to implement the chosen algorithm
  • A context forwards requests from its clients to its strategy
behavioral patterns strategy applicability
Behavioral Patterns: Strategy: Applicability
  • Many related classes differ only in their behavior
  • You need different variants of an algorithm
  • An algorithm uses data that clients should not know about
  • A class defines many behaviors, and these appear as multiple conditional statements in its operations
behavioral patterns strategy consequences
Behavioral Patterns: Strategy: Consequences
  • Families of related algorithms
  • Strategies eliminate conditional statements
  • Clients must be aware of different Strategies
behavioral patterns template method intent
Behavioral Patterns: Template Method: Intent
  • 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
behavioral patterns template method participants
Behavioral Patterns: Template Method: Participants
  • AbstractClass (Application) - defines abstract primitive operations that concrete abstract subclasses define to implement steps of the algorithm, and implements a template method defining the skeleton of an algorithm
  • ConcreteClass (MyApplication) - implements the primitive operations to carry out subclass-specific steps of the algorithm
behavioral patterns template method structure
Behavioral Patterns: Template Method: Structure
  • ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm
behavioral patterns template method applicability
Behavioral Patterns: Template Method: Applicability
  • To implement the invariant parts of an algorithm once and leave it up to the subclasses to implement the behavior that can vary
  • When common behavior among subclasses should be factored and localized in a common class to avoid duplication
behavioral patterns template method consequences
Behavioral Patterns: Template Method: Consequences
  • Template methods are a fundamental technique for code reuse
behavioral patterns visitor intent
Behavioral Patterns: Visitor: Intent
  • Represent and define a new operation to be performed on the elements of an object structure without changing the classes of the elements on which it operates
behavioral patterns visitor participants
Behavioral Patterns: Visitor: Participants
  • Visitor - declares a Visit operation for each class of ConcreteElement in the object structure
  • ConcreteVisitor - implements each operation declared by Visitor
  • Element - defines an Accept operation that takes a visitor as an argument
  • ConcreteElement - implements an Accept operation that takes a visitor as an argument
  • ObjectStructure - can enumerate its elements and may provide a high-level interface to allow the visitor to visit its elements
behavioral patterns visitor structure
Behavioral Patterns: Visitor: Structure
  • Client creates ConcreteVisitor, traverses the object structure, visiting each element with the Visitor
  • When an element is visited, it calls the Visitor operation that corresponds to its class
behavioral patterns visitor applicability
Behavioral Patterns: Visitor: Applicability
  • An object structure contains many classes of objects with different interfaces, and you want to perform operations on these objects that depend on their concrete classes
  • The classes defining the object structure rarely change, but you often want to define new operations over the structure
behavioral patterns visitor consequences
Behavioral Patterns: Visitor: Consequences
  • Visitor makes adding new operations easy
  • A Visitor gathers related operations and separates unrelated ones
behavioral patterns summary
Behavioral Patterns: Summary


  • describe not just patterns of objects or classes but also the patterns of communication between them
  • shift the focus away from flow of control allowing to concentrate just on the way the objects are interconnected
  • How does the use of pattern Benefits the Software Development Process.?
  • Patterns encapsulate knowledge that often takes years of experience to learn.
  • Patterns teach how to solve hard problems, how to recognize when a solution is appropriate (or not).
  • What to expect from that solution and why it works.
  • Patterns enable reuse of ideas, not just code.
  • However, most importantly, patterns create a common language that simplifies communication of complex topics.
  • At present, the software community is using pattern largely for software architecture and design.
  • More recently the software community is using pattern also for software development processes and o organizations.
  • Several object-oriented software design notations/methods have added support for the modeling and representation of design patterns.
pattern abstractions
Pattern Abstractions
  • A categorical classification of a set of patterns, such as software design, architectural, process, etc.

Currently, published software patterns exist for:

  • Software design and architecture.
  • Software languages (language-specific patterns are often called idioms).
  • Software processes.
  • Software management.
  • Software testing.
  • Business systems analysis.
  • Corporate organization and reengineering, and.
  • The End.