Design Patterns (DP)

115
Design Patterns (DP) By P. S. Suryateja Asst. Professor CSE Dept Vishnu Institute of Technology Erich Gamma Richard Helm Ralph Johnson John Vlissides Gang of Four (GOF)

description

Gang of Four (GOF). Richard Helm. Ralph Johnson. John Vlissides. Erich Gamma. Design Patterns (DP). By P. S. Suryateja Asst. Professor CSE Dept Vishnu Institute of Technology. Objectives. Know what are design patterns? Know about GOF patterns. How to select and use a pattern? - PowerPoint PPT Presentation

Transcript of Design Patterns (DP)

Page 1: Design Patterns (DP)

Design Patterns (DP)

By P. S. Suryateja

Asst. Professor

CSE Dept

Vishnu Institute of Technology

ErichGamma

RichardHelm

RalphJohnson

JohnVlissides

Gang of Four (GOF)

Page 2: Design Patterns (DP)

Objectives

• Know what are design patterns?• Know about GOF patterns.• How to select and use a pattern?• How to apply a pattern?

Page 3: Design Patterns (DP)

Outline

• Introduction to design patterns– What is a design pattern?– Need of design patterns– Use of design patterns– Design patterns in Smalltalk MVC– Describing design patterns– Catalog of design patterns– Organizing the catalog– How to select a design pattern?– How to use a design pattern?

Page 4: Design Patterns (DP)

Outline (cont…)

• Creational patterns– Introduction– Singleton– Abstract Factory– Factory Method– Builder– Prototype

Page 5: Design Patterns (DP)

Outline (cont…)

• Structural Patterns

Page 6: Design Patterns (DP)

Introduction to Design Patterns

Page 7: Design Patterns (DP)

What is a design pattern (DP)?“Each pattern describes a problem which occurs overand over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.”

- Christopher Alexander

Design patterns are repeatable / reusable solutions to commonly occurring problems in a certain context in software design.

Page 8: Design Patterns (DP)

What is a design pattern (DP)? (cont…)

• Pattern name

• Problem

• Solution

• Consequences

Four essential elements of a pattern:

Page 9: Design Patterns (DP)

Need for design patterns

• Designing reusable object-oriented software (API’s) is hard.

• Experienced designers Vs novice designers.

• Patterns make object-oriented software flexible, elegant and reusable.

• Solved a problem previously but don’t remember when or how?

Page 10: Design Patterns (DP)

Use of design patterns

• Make it easier to reuse successful designs and architectures.

• Make it easy for the new developers to design software.

• Allows to choose different design alternatives to make the software reusable.

• Helps in documenting and maintaining the software.

To get a design “right”, faster.

Page 11: Design Patterns (DP)

Why should we use DP’s?

These are already tested and proven solutions used by many

experienced designers.

Page 12: Design Patterns (DP)

MVC Architecture

Page 13: Design Patterns (DP)

Design Patterns in Smalltalk MVC

Page 14: Design Patterns (DP)

Describing design patterns

1. Pattern name and classification

2. Intent

3. Also known as

4. Motivation

5. Applicability

6. Structure

7. Participants

8. Collaborations

Page 15: Design Patterns (DP)

Describing design patterns (cont…)

9. Consequences

10. Implementation

11. Sample code

12. Known uses

13. Related patterns

Page 16: Design Patterns (DP)

Catalog of design patterns

1. Abstract Factory

2. Adapter

3. Bridge

4. Builder

5. Chain of Responsibility

6. Command

7. Composite

8. Decorator

9. Façade

10. Factory Method

Page 17: Design Patterns (DP)

Catalog of design patterns (cont…)

11. Flyweight

12. Interpreter

13. Iterator

14. Mediator

15. Memento

16. Observer

17. Prototype

18. Proxy

19. Singleton

20. State

Page 18: Design Patterns (DP)

Catalog of design patterns (cont…)

21. Strategy

22. Template Method

23. Visitor

Page 19: Design Patterns (DP)

Abstract Factory

Page 20: Design Patterns (DP)

Adapter

Page 21: Design Patterns (DP)

Bridge

Page 22: Design Patterns (DP)

Builder

Page 23: Design Patterns (DP)

Chain of Responsibility

Page 24: Design Patterns (DP)

Command

Page 25: Design Patterns (DP)

Composite

Page 26: Design Patterns (DP)

Decorator

Page 27: Design Patterns (DP)

Façade

Page 28: Design Patterns (DP)

Factory Method

Page 29: Design Patterns (DP)

Flyweight

Page 30: Design Patterns (DP)

Interpreter

Page 31: Design Patterns (DP)

Iterator

Page 32: Design Patterns (DP)

Mediator

Page 33: Design Patterns (DP)

Memento

Page 34: Design Patterns (DP)

Observer

Page 35: Design Patterns (DP)

Prototype

Page 36: Design Patterns (DP)

Proxy

Page 37: Design Patterns (DP)

Singleton

Page 38: Design Patterns (DP)

State

Page 39: Design Patterns (DP)

Strategy

Page 40: Design Patterns (DP)

Template Method

Page 41: Design Patterns (DP)

Visitor

Page 42: Design Patterns (DP)

Organizing the catalog

Page 43: Design Patterns (DP)

How to select a design pattern

• Consider how design patterns solve design problems

• Scan intent sections

• Study how patterns interrelate

• Study patterns of like purpose

• Examine a cause of redesign

• Consider what should be variable in your design

Page 44: Design Patterns (DP)

Relationships between patterns

Page 45: Design Patterns (DP)

How to use a design pattern

1. Read the pattern once through for a overview.

2. Study the structure, participants and collaborations sections.

3. Look at the sample code section to see a concrete example of the pattern in action.

4. Choose names for pattern participants that are meaningful in the application context.

5. Define the classes.

6. Define application-specific names for the operations in the pattern.

7. Implement the operations to carry out the responsibilities and collaborations in the pattern.

Page 46: Design Patterns (DP)

Creational Patterns

Page 47: Design Patterns (DP)

Introduction

• Deals with how objects are created.

• Increase the system’s flexibility in terms of what, who, how and when the object is created.

• Further classified into two types:1. Class-creational patterns

2. Object-creational patterns

• Five creational patterns:1. Abstract Factory

2. Builder

3. Factory Method

4. Prototype

5. Singleton

Page 48: Design Patterns (DP)

Singleton Pattern

• To create exactly one object of a class and to provide a global point of access to it.

Structure

Page 49: Design Patterns (DP)

Singleton Pattern (cont…)Non-Software Example

Page 50: Design Patterns (DP)

Singleton Pattern (cont…)

Motivation:

1) Need to create exactly one user interface object.

2) Need to create only one print spooler.

Page 51: Design Patterns (DP)

Singleton Pattern (cont…)

Applicability:

Singleton Pattern can be used when:

1)There must be exactly one instance of a class and to provide a global point of access to it.

2)When the sole instance should be extensible by sub classing, and clients should be able to use the extended instance without modifying its code.

Page 52: Design Patterns (DP)

Singleton Pattern (cont…)

Participants:

Consists of a “Singleton” class with the following members:

1)A static data member

2)A private constructor

3)A static public method that returns a reference to the static data member.

Page 53: Design Patterns (DP)

Singleton Pattern (cont…)

Collaborations:

Clients access the singleton instance solely through the singleton’s class operation.

Page 54: Design Patterns (DP)

Singleton Pattern (cont…)

Consequences:• Controlled access to sole instance.• Reduced name space.• Permits refinement of operations and

representation.• Permits a variable number of instances.

Page 55: Design Patterns (DP)

Singleton Pattern (cont…)Implementation:

class Singleton{

private static Singleton instance;private Singleton(){

...}public static synchronized Singleton getInstance(){

if (instance == null)instance = new Singleton();

return instance;}...public void doOperation(){

...}

}

Page 56: Design Patterns (DP)

Singleton Pattern (cont…)

Sample code:

Design a small ATM printing application which can generate multiple types of statements of the transaction including Mini Statement, Detailed statement etc. However the customer should be aware of the creation of these statements. Ensure that the memory consumption is minimized.

Page 57: Design Patterns (DP)

Singleton Pattern (cont…)Real World Example

Page 58: Design Patterns (DP)

Singleton Pattern (cont…)

Code for StatementFactory class is as shown below:

public class StatementFactory extends Factory{

private static StatementFactory uniqueInstance;

private StatementFactory() {}

public static StatementFactory getUniqueInstance(){

if (uniqueInstance == null){

uniqueInstance = new StatementFactory();System.out.println("Creating a new StatementFactory instance");

}return uniqueInstance;

}

Page 59: Design Patterns (DP)

Singleton Pattern (cont…)

public StatementType createStatements(String selection){

if (selection.equalsIgnoreCase("detailedStmt")){

return new DetailedStatement(); }

else if (selection.equalsIgnoreCase("miniStmt")){

return new MiniStatement(); }

throw new IllegalArgumentException("Selection doesnot exist"); }}

Page 60: Design Patterns (DP)

Singleton Pattern (cont…)

Related Patterns:

Other patterns like Abstract Factory, Builder and Prototype can be implemented using the Singleton pattern.

Page 61: Design Patterns (DP)

Abstract Factory Pattern

• Provides an interface to create a family of related objects, without explicitly specifying their concrete class.

Page 62: Design Patterns (DP)

Abstract Factory Pattern (cont…)Non-Software Example

Page 63: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Also known as:

Kit

Page 64: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Motivation:

Creating interface components for different look and feels.

Page 65: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Applicability:

We should use Abstract Factory design pattern when:• The system needs to be independent of the products it works with are

created.

• The system should be configured to work with multiple families of products.

• A family of products is designed to be used together and this constraint is needed to be enforced.

• A library of products is to be provided and only their interfaces are to be revealed but not their implementations.

Page 66: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Participants:

The classes that participate in the Abstract Factory are:• AbstractFactory: Declares an interface of operations that create abstract

products.

• ConcreteFactory: Implements operations to create concrete products.

• AbstractProduct: Declares an interface for a type of product objects.

• Product: Defines a product to be created by the corresponding ConcreteFactory. It implements the AbstractProduct interface.

• Client: Uses the interfaces declared by the AbstractFactory and AbstractProduct classes.

Page 67: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Collaborations:• The ConcreteFactory class creates products

objects having a particular implementation. To create different product, the client should use a different concrete factory.

• AbstractFactory defers creation of product objects to its ConcreteFactory subclass.

Page 68: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Consequences:

Following are the benefits and liabilities of Abstract Factory pattern:

• It isolates concrete classes.

• It makes exchanging product families easy.

• It creates consistency among products.

• Supporting new kinds of products is difficult.

Page 69: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Implementation:

abstract class AbstractProductA {

public abstract void operationA1();public abstract void operationA2();

}

Page 70: Design Patterns (DP)

Abstract Factory Pattern (cont…)class ProductA1 extends AbstractProductA {

ProductA1(String arg){

System.out.println("Hello "+arg);} // Implement the code herepublic void operationA1() { };public void operationA2() { };

}class ProductA2 extends AbstractProductA {

ProductA2(String arg){

System.out.println("Hello "+arg);} // Implement the code herepublic void operationA1() { };public void operationA2() { };

}

Page 71: Design Patterns (DP)

Abstract Factory Pattern (cont…)

abstract class AbstractProductB {

public abstract void operationB1();public abstract void operationB2();

}

Page 72: Design Patterns (DP)

Abstract Factory Pattern (cont…)class ProductB1 extends AbstractProductB {

ProductB1(String arg){

System.out.println("Hello "+arg);} // Implement the code here

} class ProductB2 extends AbstractProductB {

ProductB2(String arg){

System.out.println("Hello "+arg);} // Implement the code here

}

Page 73: Design Patterns (DP)

Abstract Factory Pattern (cont…)abstract class AbstractFactory {

abstract AbstractProductA createProductA();abstract AbstractProductB createProductB();

}

Page 74: Design Patterns (DP)

Abstract Factory Pattern (cont…)class ConcreteFactory1 extends AbstractFactory {

AbstractProductA createProductA(){

return new ProductA1("ProductA1");}AbstractProductB createProductB(){

return new ProductB1("ProductB1");}

}class ConcreteFactory2 extends AbstractFactory {

AbstractProductA createProductA(){

return new ProductA2("ProductA2");}AbstractProductB createProductB(){

return new ProductB2("ProductB2");}

}

Page 75: Design Patterns (DP)

Abstract Factory Pattern (cont…)class FactoryMaker {

private static AbstractFactory pf=null;static AbstractFactory getFactory(String choice){

if(choice.equals("a")){

pf=new ConcreteFactory1();}else if(choice.equals("b")){

pf=new ConcreteFactory2();} return pf;

}}

Page 76: Design Patterns (DP)

Abstract Factory Pattern (cont…)public class Client{

public static void main(String args[ ]){

AbstractFactory pf=FactoryMaker.getFactory("a");AbstractProductA product=pf.createProductA();//more function calls on product

}}

Page 77: Design Patterns (DP)

Abstract Factory Pattern (cont…)Real World Example

Page 78: Design Patterns (DP)

Abstract Factory Pattern (cont…)Sample Code:

public interface Window{

public void setTitle(String text); public void repaint();}

Page 79: Design Patterns (DP)

Abstract Factory Pattern (cont…)

//ConcreteProductA1public class MSWindow implements Window{

public void setTitle(){

//MS Windows specific behaviour }public void repaint(){

//MS Windows specific behaviour }

}

Page 80: Design Patterns (DP)

Abstract Factory Pattern (cont…)//ConcreteProductA2public class MacOSXWindow implements Window{

public void setTitle(){

//Mac OSX specific behaviour }public void repaint(){

//Mac OSX specific behaviour }

}

Page 81: Design Patterns (DP)

Abstract Factory Pattern (cont…)

public interface AbstractWidgetFactory {

public Window createWindow();}

Page 82: Design Patterns (DP)

Abstract Factory Pattern (cont…)//ConcreteFactory1public class MsWindowsWidgetFactory {

//create an MSWindow public Window createWindow(){

MSWindow window = new MSWindow(); return window;

}} //ConcreteFactory2public class MacOSXWidgetFactory {

//create a MacOSXWindow public Window createWindow(){

MacOSXWindow window = new MacOSXWindow(); return window;

}}

Page 83: Design Patterns (DP)

Abstract Factory Pattern (cont…)public class GUIBuilder {

public void buildWindow(AbstractWidgetFactory widgetFactory){

Window window = widgetFactory.createWindow(); window.setTitle("New Window");

}}

Page 84: Design Patterns (DP)

Abstract Factory Pattern (cont…)

public class Main{

public static void main(String[] args) {

GUIBuilder builder = new GUIBuilder();AbstractWidgetFactory widgetFactory = null;//check what platform we're on if(Platform.currentPlatform()=="MACOSX"){

widgetFactory = new MacOSXWidgetFactory();}else{

widgetFactory = new MsWindowsWidgetFactory();}builder.buildWindow(widgetFactory);

}}

Page 85: Design Patterns (DP)

Abstract Factory Pattern (cont…)

Related Patterns:

AbstractFactory classes are often implemented with factory methods but they can also be implemented using Prototype. A concrete factory is often a Singleton.

Page 86: Design Patterns (DP)

Factory Method Pattern

• Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Page 87: Design Patterns (DP)

Factory Method Pattern (cont…)Non-Software Example

Page 88: Design Patterns (DP)

Factory Method Pattern (cont…)

Also known as:

Virtual constructor

Page 89: Design Patterns (DP)

Factory Method Pattern (cont…)

Motivation:

Document application

Page 90: Design Patterns (DP)

Factory Method Pattern (cont…)

Applicability:• A class can’t anticipate the class of objects it

must create.

• A class wants its sub classes to specify the objects it creates.

• Classes delegate responsibility to one of several helper subclasses.

Page 91: Design Patterns (DP)

Factory Method Pattern (cont…)

Participants:• Product: Defines the interface of objects the factory method

creates.

• ConcreteProduct: Implements the Product interface.

• Creator: Declares the factory method, which returns an object of the type Product.

• ConcreteCreator: Overrides the factory method to return an instance of a ConcreteProduct.

Page 92: Design Patterns (DP)

Factory Method Pattern (cont…)

Collaborations:

Creator relies on its subclasses to provide an implementation for the factory method so that it returns an instance of the appropriate ConcreteProduct class.

Page 93: Design Patterns (DP)

Factory Method Pattern (cont…)

Consequences:

•The main reason for which the factory pattern is used is that it introduces a separation between the application and a family of classes.

•It provides customization hooks.

•The factory has to be used for a family of objects.

Page 94: Design Patterns (DP)

Factory Method Pattern (cont…)Implementation:

public interface Product { } public class ConcreteProduct implements Product { } public abstract class Creator {

public void anOperation() {

Product product = factoryMethod();}protected abstract Product factoryMethod();

} public class ConcreteCreator extends Creator {

protected Product factoryMethod() {

return new ConcreteProduct();}

}

Page 95: Design Patterns (DP)

Factory Method Pattern (cont…)Real World Example

Page 96: Design Patterns (DP)

Factory Method Pattern (cont…)

Related patterns:• Abstract Factory is often implemented with factory

methods.

• Factory methods are usually called within Template Methods. In the Document example above, NewDocument() is a template method.

• Prototypes don’t require subclassing Creator. Instead, they often require an Initialize operation on the product class. Factory Method doesn’t require such operation.

Page 97: Design Patterns (DP)

Builder Pattern

• Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Page 98: Design Patterns (DP)

Builder Pattern (cont…)Non-Software Example

Page 99: Design Patterns (DP)

Builder Pattern (cont…)Motivation:

Text Converter

Page 100: Design Patterns (DP)

Builder Pattern (cont…)

Use the Builder pattern when:• The algorithm for creating a complex object

should be independent of the parts that make up the object and how they are assembled.

• The construction process must allow different representations for the object that is constructed.

Applicability:

Page 101: Design Patterns (DP)

Builder Pattern (cont…)

• Builder: Provides an abstract interface for creating parts of a Product object.

• ConcreteBuilder: Constructs and assembles the parts of the Product by implementing the Builder interface.

• Director: Constructs an object using the Builder interface.

• Product: Represents the complex object under construction.

Participants:

Page 102: Design Patterns (DP)

Builder Pattern (cont…)

The benefits and pitfalls of Builder pattern are:• It let’s you vary the product’s internal

representation.• It isolates code for construction and

representation.• It gives you finer control over the

construction process.

Consequences:

Page 103: Design Patterns (DP)

Builder Pattern (cont…)

//Abstract Builderclass abstract class TextConverter {

abstract void convertCharacter(char c);abstract void convertParagraph();

} // Productclass ASCIIText {

public void append(char c){ //Implement the code here }

}

Implementation:

Page 104: Design Patterns (DP)

Builder Pattern (cont…)//Concrete Builderclass ASCIIConverter extends TextConverter {

ASCIIText asciiTextObj; //resulting product/*converts a character to target representation and appends to the resulting

object*/void convertCharacter(char c){

char asciiChar = new Character(c).charValue();//gets the ascii characterasciiTextObj.append(asciiChar);

}void convertParagraph() {}ASCIIText getResult(){

return asciiTextObj;}

}

Page 105: Design Patterns (DP)

Builder Pattern (cont…)

//This class abstracts the document objectclass Document{

static int value;char token;public char getNextToken(){

//Get the next tokenreturn token;

}}

Page 106: Design Patterns (DP)

Builder Pattern (cont…)//Directorclass RTFReader {

private static final char EOF='0'; //Delimitor for End of Filefinal char CHAR='c';final char PARA='p';char t;TextConverter builder;RTFReader(TextConverter obj){

builder=obj;}

Page 107: Design Patterns (DP)

Builder Pattern (cont…)

void parseRTF(Document doc){

while ((t=doc.getNextToken())!= EOF){

switch (t){

case CHAR: builder.convertCharacter(t);case PARA: builder.convertParagraph();

}}

}}

Page 108: Design Patterns (DP)

Builder Pattern (cont…)//Clientpublic class Client{

void createASCIIText(Document doc){

ASCIIConverter asciiBuilder = new ASCIIConverter();RTFReader rtfReader = new RTFReader(asciiBuilder);rtfReader.parseRTF(doc);ASCIIText asciiText = asciiBuilder.getResult();

}public static void main(String args[]){

Client client=new Client();Document doc=new Document();client.createASCIIText(doc);system.out.println("This is an example of Builder Pattern");

}}

Page 109: Design Patterns (DP)

Builder Pattern (cont…)Real World Example

Waiter

Page 110: Design Patterns (DP)

Prototype Pattern

• To specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Page 111: Design Patterns (DP)

Prototype Pattern (cont…)

Page 112: Design Patterns (DP)

Prototype Pattern (cont…)

Participants:

• Client - creates a new object by asking a prototype to clone itself.

• Prototype - declares an interface for cloning itself.

• ConcretePrototype - implements the operation for cloning itself.

Page 113: Design Patterns (DP)

Prototype Pattern (cont…)Implementation

abstract class AbstractProduct implements Cloneable {

public static AbstractProduct thePrototype;public static AbstractProduct makeProduct(){

try {

return (AbstractProduct) thePrototype.clone(); }

catch(CloneNotSupportedException e){

return null; }}

}

Page 114: Design Patterns (DP)

Prototype Pattern (cont…)class ConcreteProductA extends AbstractProduct { } class ConcreteProductB extends AbstractProduct { } public class PrototypeDemo {

public static void main(String[] args) {

AbstractProduct.thePrototype = new ConcreteProductA();AbstractProduct product = AbstractProduct.makeProduct();System.out.println(product);

}}

Page 115: Design Patterns (DP)

Prototype Pattern (cont…)Real World Example