factory method, strategy pattern & chain of responsibilities

51
Factory Method Pattern Strategy Pattern Proxy Pattern Chain of Responsibilities Memento Pattern

Upload: babak

Post on 25-May-2015

393 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Factory method, strategy pattern & chain of responsibilities

Factory Method PatternStrategy Pattern

Proxy Pattern

Chain of ResponsibilitiesMemento Pattern

Page 2: Factory method, strategy pattern & chain of responsibilities

2

Factory Method(Creational)

Page 3: Factory method, strategy pattern & chain of responsibilities

3

Factory MethodName: Factory MethodIntent: Define an interface for creating an

object, but let subclasses decide which class to instantiate. Defer instantiation to subclasses.

Problem: A class needs to instantiate a derivation of another class, but doesn't know which one. Factory Method allows a derived class to make this decision.

Solution: Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.

Page 4: Factory method, strategy pattern & chain of responsibilities

4

Basic Structure

Product is the interface for the type of object that the Factory Method creates. Creator is the interface that defines the Factory Method.

Product<<<interface>>>

ConcreteProduct

Creator

FactoryMethod()

<<<interface>>>

ConcreteCreator

FactoryMethod()

<<instantiates>>

Page 5: Factory method, strategy pattern & chain of responsibilities

5

A Case Study: Database Connections

You want to connect to a database but you want to decide at run time which type of database it is (i.e. SQL, Oracle, MySQL etc.)

Apply Factory Method

Page 6: Factory method, strategy pattern & chain of responsibilities

6

Structure of Case study

ConnectionFactory

createConnection() : Connection

<<<interface>>>

MyConnectionFactory

createConnection() : Connection

Connection

description()open()close()

<<<interface>>>

SQLConnection MySQLConnection OracleConnection<<instantiates>>

Instantiates SQLConnection / MySQLConnection / OracleConnection

Page 7: Factory method, strategy pattern & chain of responsibilities

7

Implementation: ConnectionFactory

public interface ConnectionFactory{public Connection createConnection();

}class MyConnectionFactory implements ConnectionFactory{

public String type;public MyConnectionFactory(String t){

type = t; }

public Connection createConnection(){if(type.equals("Oracle")){

return new OracleConnection(); }else if(type.equals("SQL")){

return new SQLConnection(); }else{ return new MySQLConnection(); }

}}

Page 8: Factory method, strategy pattern & chain of responsibilities

8

Implementation: Connection

public interface Connection{public String description();public void open();public void close();

}class SQLConnection implements Connection{

public String description(){ return "SQL";} }class MySQLConnection implements

Connection{public String description(){ return "MySQL” ;} }

class OracleConnection implements Connection{

public String description(){ return "Oracle"; } }

These three implementing classes should have definition for Open & Close Methods of above interface as well to be concrete.

Page 9: Factory method, strategy pattern & chain of responsibilities

9

Implementation: TestConnectionFactory

class TestConnectionFactory{public static void main(String[]args){

MyConnectionFactory con = new MyConnectionFactory("My SQL");

Connection con2 = con.createConnection();

System.out.println("Connection Created: ");

System.out.println(con2.description());}

}

Page 10: Factory method, strategy pattern & chain of responsibilities

10

Strategy Pattern

Page 11: Factory method, strategy pattern & chain of responsibilities

11

Strategy Pattern

Name: StrategyIntent: Define a family of algorithms,

encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Problem: How to design for varying, but related, algorithms or policies?

Solution: Define each algorithm/policy/strategy in a separate class, with a common interface.

Page 12: Factory method, strategy pattern & chain of responsibilities

12

Basic Structure

ConcreteStrategyA ConcreteStrategyB

ContextStrategy

Algorithm()

Page 13: Factory method, strategy pattern & chain of responsibilities

13

Participants

Strategy : declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.

ConcreteStrategy: implements the algorithm using the Strategy interface.

Context : is configured with a ConcreteStrategy object. maintains a reference to a Strategy object. may define an interface that lets Strategy

access its data.

Page 14: Factory method, strategy pattern & chain of responsibilities

14

Case StudyWe are developing an e-commerce application

where we need to calculate Tax…there are two tax strategies…Tax rate is 10% for old citizens and 15% otherwise.

Page 15: Factory method, strategy pattern & chain of responsibilities

15

Case Study Structure

Citizen OldCitizen

TaxStrategy

calcTax()

<<<interface>>>

ClientTaxContext

setStrategy() : TaxStrategycalculateTax()

Page 16: Factory method, strategy pattern & chain of responsibilities

16

Implementation: TaxStrategy

public interface TaxStrategy{public void calcTax();

}class Citizen implements TaxStrategy{

public void calcTax(){System.out.println("Tax Deduction @

15%");}}

class OldCitizen implements TaxStrategy{public void calcTax(){

System.out.println("Tax Deduction @ 10%");}}

Page 17: Factory method, strategy pattern & chain of responsibilities

17

Implementation: TaxContext

class TaxContext{

private TaxStrategy TS;

public void setStrategy(TaxStrategy ts){ TS=ts; }

public void calculateTax(){ TS.calcTax(); }}

class Client{

public static void main(String[]args){

TaxContext cont = new TaxContext();

cont.setStrategy(new Citizen());

cont.calculateTax();

}

}

Page 18: Factory method, strategy pattern & chain of responsibilities

18

How to Create Strategies

There are different Taxing algorithms or strategies, and they change over time. Who should create the strategy?

A straightforward approach is to apply the Factory pattern

Page 19: Factory method, strategy pattern & chain of responsibilities

19

Strategy and Factory Method

Product<<<interface>>>

ConcreteProduct

Creator

FactoryMethod()

<<<interface>>>

ConcreteCreator

FactoryMethod()

<<instantiates>>

ConcreteStrategyA ConcreteStrategyB

Strategy

Algorithm()

Context

Page 20: Factory method, strategy pattern & chain of responsibilities

20

Case Study Structure

StrategyFactory

getStrategy() : TaxStrategy

<<<interface>>>

MyStrategyCitizen OldCitizen

TaxStrategy

calcTax()

<<<interface>>>TaxContext

setStrategy() : TaxStrategycalculateTax()

Client

<<instantiates>>

Page 21: Factory method, strategy pattern & chain of responsibilities

21

Implementation: StrategyFactorypublic interface StrategyFactory{

public TaxStrategy getStrategy();

}

class MyStrategy implements StrategyFactory{

String type;

public MyStrategy(String t){ type=t; }

public TaxStrategy getStrategy(){

if(type.equals("Citizen"))

return new Citizen();

else

return new OldCitizen();} }

Page 22: Factory method, strategy pattern & chain of responsibilities

22

Implementation: Clientclass Client{

public static void main(String[]args){MyStrategy m = new

MyStrategy("Citizen");TaxContext cont = new TaxContext();cont.setStrategy(m.getStrategy());cont.calculateTax();

}}

Page 23: Factory method, strategy pattern & chain of responsibilities

23

Proxy Pattern

Page 24: Factory method, strategy pattern & chain of responsibilities

24

Proxy Pattern

Name: ProxyIntent: Provide a surrogate or placeholder for

another object to control access to it.Problem: You want to control the access to an

object for different reasons. You may want to delay the creation / initialization of expensive objects or you may want to provide a local representation of a remote object.

Solution: Provide a Stub / placeholder for actual object.

Page 25: Factory method, strategy pattern & chain of responsibilities

25

Basic Structure

Client Subject

someOperation()

<<<interface>>>

Proxy

someOperation()

RealSubject

someOperation()

RealSubject someOperation()

Page 26: Factory method, strategy pattern & chain of responsibilities

26

ParticipantsSubject - Interface implemented by the

RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.

Proxy- Maintains a reference that allows the Proxy to access the RealSubject. Implements the same interface implemented by the RealSubject so that the Proxy can be substituted for the RealSubject. Controls access to the RealSubject and may be responsible for its creation and deletion.

RealSubject- the real object that the proxy represents.

Page 27: Factory method, strategy pattern & chain of responsibilities

27

Case Study

Consider an image viewer program that lists and displays high resolution photos. The program has to show a list of all photos however it does not need to display the actual photo until the user selects an image item from a list.

Page 28: Factory method, strategy pattern & chain of responsibilities

28

Case Study Structure

ProxyImage

showImage() : void

HRImage

showImage() : void

ImageViewer Image

showImage() : void

<<<interface>>>

showImage() displays the Image only when needed

Page 29: Factory method, strategy pattern & chain of responsibilities

29

Implementation: Imagepublic interface Image{

public void showImage();

}

class HRImage implements Image{

public HRImage(){

System.out.println("loading a High Resolution image");

}

public void showImage(){

System.out.println("Showing a High Resolution Image");

}

}

Page 30: Factory method, strategy pattern & chain of responsibilities

30

Implementation: ProxyImageclass ProxyImage implements Image{

private Image proxyImage;public ProxyImage(){ System.out.println("Loading a proxy image");}public void showImage(){

proxyImage = (HRImage)new HRImage();proxyImage.showImage();} }

class ImageViewer{public static void main(String[]args){

Image HRImage1 = new ProxyImage();Image HRImage2 = new ProxyImage();Image HRImage3 = new ProxyImage();

HRImage1.showImage();} }

Page 31: Factory method, strategy pattern & chain of responsibilities

31

Applicability

Virtual Proxies: delaying the creation and initialization of expensive objects until needed, where the objects are created on demand

Remote Proxies: providing a local representation for an object that is in a different address space. A common example is Java RMI stub objects. The stub object acts as a proxy where invoking methods on the stub would cause the stub to communicate and invoke methods on a remote object (called skeleton) found on a different machine.

Protection Proxies: where a proxy controls access to RealSubject methods, by giving access to some objects while denying access to others.

Page 32: Factory method, strategy pattern & chain of responsibilities

32

Chain of Responsibility

Page 33: Factory method, strategy pattern & chain of responsibilities

33

Chain of Responsibility Pattern

Name: 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.

Problem: A group of classes each have processes to run in turn, but there is no way to directly determine in which class order each should run its process

Solution: Use a chained association of classes that have interdependence on each other to define the order of operations

Page 34: Factory method, strategy pattern & chain of responsibilities

34

Basic Structure

ConcreteHandlerA ConcreteHandlerB

Client Handler

HandleRequest()

<<<interface>>>-Successor

Page 35: Factory method, strategy pattern & chain of responsibilities

35

Participants

Handler defines an interface for handling requests.

ConcreteHandler handles requests it is responsible for. can access its successor. if the ConcreteHandler can handle the request,

it does so; otherwise it forwards the request to its successor.

Page 36: Factory method, strategy pattern & chain of responsibilities

36

Case Study

We want to develop a Help System for a Bank. The client can get Help about Accounts, Credit / Debit Cards, Bank Loan etc.

Page 37: Factory method, strategy pattern & chain of responsibilities

37

Case Study Structure

AccountHelp CardHelp LoanHelp

Client

GenHelp

HelpInterface

getHelp()

<<<interface>>>All Classes have HelpInterface Object

Page 38: Factory method, strategy pattern & chain of responsibilities

38

Implementation: HelpInterface

interface HelpInterface{public void getHelp(int id);

}class AccountHelp implements HelpInterface{

final int ACCOUNT_HELP=1;HelpInterface successor;public AccountHelp(HelpInterface s){ successor=s; }public void getHelp(int id){

if(id!=ACCOUNT_HELP)successor.getHelp(id);

elseSystem.out.println("Account Help..."); } }

Page 39: Factory method, strategy pattern & chain of responsibilities

39

Implementation: CardHelp

class CardHelp implements HelpInterface{

final int CARD_HELP=2;

HelpInterface successor;

public CardHelp(HelpInterface s){ successor=s; }

public void getHelp(int id){

if(id!=CARD_HELP) successor.getHelp(id);

else System.out.println("Card Help...");}}

class LoanHelp implements HelpInterface{

final int LOAN_HELP=3;

HelpInterface successor;

public LoanHelp(HelpInterface s){ successor=s; }

public void getHelp(int id){

if(id!=LOAN_HELP) successor.getHelp(id);

else System.out.println("Loan Help..."); } }

Page 40: Factory method, strategy pattern & chain of responsibilities

40

Implementation: GenHelp

class GenHelp implements HelpInterface{public GenHelp(){ }public void getHelp(int id){

System.out.println("General Help...");} }

class Client{public static void main(String[]args){

GenHelp gh = new GenHelp();LoanHelp lh = new LoanHelp(gh);CardHelp ch = new CardHelp(lh);AccountHelp ah = new AccountHelp(ch);

ah.getHelp(3);}

}

Page 41: Factory method, strategy pattern & chain of responsibilities

41

Memento Pattern

Page 42: Factory method, strategy pattern & chain of responsibilities

42

Memento PatternName: MementoIntent: Without violating encapsulation,

capture and externalize an object's internal state so that the object can be restored to this state later.

Problem: A class needs to have its internal state captured and then restored without violating the class’s encapsulation

Solution: Use a memento and a caretaker to capture and store the object’s state

Page 43: Factory method, strategy pattern & chain of responsibilities

43

ParticipantsMemento: stores internal state of the

Originator object. The memento may store as much or as little of the originator's internal state as necessary at its originator's discretion.

Originator: creates a memento containing a snapshot of its current internal state. uses the memento to restore its internal state.

Caretaker: is responsible for the memento's safekeeping. never operates on or examines the contents of a memento.

Page 44: Factory method, strategy pattern & chain of responsibilities

44

Basic Structure

Originator

state

setMemento()createMemento()

return new Memento (state) state = m.State

CareTakerMemento

State

Page 45: Factory method, strategy pattern & chain of responsibilities

45

Case Study

We want to develop a Simple Calculator that can restore previous calculations.

Page 46: Factory method, strategy pattern & chain of responsibilities

46

Case Study Structure

Calculator

num1 : Integernum2 : IntegerResult : Integeroperation : String

Calculator()createMemento() : Memento

Memento

num1 : Integernum2 : IntegerResult : Integeroperation : String

Memento()

CareTaker

undo : Listm : Memento

CareTaker()addMemento() : Mementoprevious()

Page 47: Factory method, strategy pattern & chain of responsibilities

47

Implementation: Calculator

public class Calculator{int num1,num2,Result;String operation;public Calculator(int x, int y,String op){

num1 = x; num2 = y; operation = op;}int getResult(){

if(operation=="add") Result = num1+num2; else if(operation=="sub") Result = num1-num2; else Result = num1*num2; return Result;

}Memento createMemento(){

return new Memento(num1,num2,Result,operation); } }

Page 48: Factory method, strategy pattern & chain of responsibilities

48

Implementation: Memento

class Memento{int num1,num2,Result;String operation;

public Memento(){}public Memento(int n1,int n2, int r, String op){

num1=n1;num2=n2;Result=r;operation=op;

}

}

Page 49: Factory method, strategy pattern & chain of responsibilities

49

Implementation: CareTakerclass CareTaker{

List undo; int i; Memento m;public CareTaker(){

undo = new ArrayList(); m = new Memento();}

public void addMemento(Memento mem){ undo.add(i,mem); i++; }public void previous(){

if (undo.size() > 0) { int ct = undo.size()-1; m = (Memento)undo.get(ct); undo.remove(ct);

}System.out.println("num1: "+m.num1);System.out.println("num2: "+m.num2);System.out.println("Result: "+m.Result);System.out.println("Operation: "+m.operation); } }

Page 50: Factory method, strategy pattern & chain of responsibilities

50

Implementation: Clientclass Client{

public static void main(String[]args){CareTaker ct = new CareTaker();

Calculator cal = new Calculator(4,5,"add");System.out.println("Result is: "+ cal.getResult());ct.addMemento(cal.createMemento());

cal = new Calculator(80,55,"sub");System.out.println("Result is: "+ cal.getResult());ct.addMemento(cal.createMemento());

System.out.println("Last two Calculations are: \n");ct.previous();ct.previous();

}}

Page 51: Factory method, strategy pattern & chain of responsibilities

51

The End