Team 4 design patterns
This presentation is the property of its rightful owner.
Sponsored Links
1 / 179

TEAM 4: DESIGN PATTERNS PowerPoint PPT Presentation


  • 31 Views
  • Uploaded on
  • Presentation posted in: General

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

Download Presentation

TEAM 4: DESIGN PATTERNS

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

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.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

TEAM 4: DESIGN PATTERNS

BY

Piyush Vijayvargiya

Young Jin Kim

Bimesh Giri

Arkadiy Gorelik

SPRING 2003, COMP 680


Introduction

Introduction


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.


Solution

Solution

  • 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.


Classification of design patterns a view

Classification of design patterns ( a view)


Creational design patterns

Creational Design Patterns


Objective

Objective

  • 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.

CreationalPatterns

CreatingObject

Client

Application

request

Return object

Encapsulated


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(Color.black);//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

else

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


Team 4 design patterns

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 object.cf) (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 burger store

The Builder Pattern<Example: Burger store>


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 example house building1

The Builder Pattern<Example: House Building>

  • Class structure


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#:

    ICloneable.Clone()

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 design patterns

Structural Design Patterns


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.


Participants

PARTICIPANTS

  • 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.


Also known as wrapper

Also known as Wrapper


Implementation

IMPLEMENTATION

  • 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

corners


Team 4 design patterns

• 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)


Team 4 design patterns

• 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


Approach 1 using multiple inheritance

Approach 1 – Using Multiple Inheritance


Approach 2 using composition

Approach 2 – Using Composition


Applicability

Applicability

  • 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.


Participants1

PARTICIPANTS

  • 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.


Also known as handle body

AlsoknownasHandle/Body


Implementation1

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.


Applicability1

Applicability

  • 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.


Participants2

PARTICIPANTS

  • 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.


Structure

Structure


Implementation2

IMPLEMENTATION

  • Composite classes extend a base class that represents primitive objects.

  • The Composite class maintains a collection of components.


Example the filing system is composite

Example–The Filing System is Composite


Team 4 design patterns

  • 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.


Applicability2

Applicability

  • 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.


Participants3

PARTICIPANTS

  • 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.


Structure1

Structure


Example adding user interface decorators to visualcomponents objects

Example–Adding user interface decorators to VisualComponents objects


Applicability3

Applicability

  • 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.


Participants4

PARTICIPANTS

  • 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.


Structure2

Structure


Implementation3

IMPLEMENTATION

  • 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).


Applicability4

Applicability

  • 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.


Participants5

PARTICIPANTS

  • 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.


Team 4 design patterns

  • FlyweightFactory

    • creates and manages flyweight objects.

  • Client

    • maintains a reference to flyweight(s).

    • computes or stores the extrinsic state of flyweight(s).


Structure3

Structure


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.


Applicability5

Applicability

  • 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.


Participants6

PARTICIPANTS

  • Proxy

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


Team 4 design patterns

  • 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.


Structure4

Structure


Implementation4

IMPLEMENTATION

  • 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()


Applicability6

Applicability

  • 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 design patterns

Behavioral Design Patterns


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

BEHAVIORAL PATTERNS:

  • 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


Conclusion

Conclusion


Conclusion1

Conclusion

  • 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.


Conclusion2

Conclusion

  • 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.


Questions

Questions

  • The End.


  • Login