View
215
Download
0
Embed Size (px)
Citation preview
ECE 355 Design Patterns Tutorial ECE 355 Design Patterns Tutorial Part 3Part 3
Presented by Igor Ivković
2
Something Fun Something Fun
CreationalPatterns
StructuralPatterns
BehaviouralPatterns
http://home.earthlink.net/~huston2/dp/patterns.html
3
AgendaAgenda
Design Patterns
Factory Method
o Adapter
o Bridge
o Command
o State
o Proxy
Summary and References
4
Factory Method / 1Factory Method / 1
Intent: This method allows subclasses to decide which class is to be instantiated while defining an interface for creating an object
Also Known As: Virtual Constructor
Applicability:
– When the class of objects to be created cannot be estimated by the class creating them
– The subclasses must specify the objects created by the class
– Information about the helper subclass to which classes have delegated responsibility has to be localized
6
Factory Method / 3Factory Method / 3
Code / 1:
public class Test{
public static void main( String arg[] ){
try{ Creator creator = new
ConcreteCreator(); creator.anOperation(); }catch( Exception e ){ e.printStackTrace(); }
}
public interface Product{}http://vico.org/pages/PatronsDisseny/Pattern%20Factory%20Method/
7
Factory Method / 4Factory Method / 4
Code / 2:
// Declares the factory method, // which returns an object of type Product. // May also define a default implementation of factory // method that returns a default ConcreteProduct object, // or may call the factory method to create a Product object
public abstract class Creator{
public void anOperation(){ Product product = factoryMethod(); }
protected abstract Product factoryMethod();}
8
Factory Method / 5Factory Method / 5
Code / 3:
// Overrides the factory method to return // an instance of a ConcreteProduct.
public class ConcreteCreator extends Creator{
protected Product factoryMethod(){
return new ConcreteProduct();}
}
9
AgendaAgenda
Design Patterns
Factory Method
Adapter
o Bridge
o Command
o State
o Proxy
Summary and References
10
Adapter / 1Adapter / 1
Intent: allow classes with incompatible interfaces to work together, by converting the interface of a given class into one expected by the clients
Also Known As: Wrapper
Applicability:
– The interface of an existing class does not match the need
– The creation of a reusable class that can work with unforeseen or unrelated classes with incompatible interfaces
– Adapting interfaces of several existing subclasses is not feasible, in which case the interface of the parent class can be adapted by the object adapter
11
Adapter / 2Adapter / 2
Pattern Structure – Class Adapter:
– Uses multiple inheritance to adapt one interface to another
12
Adapter / 3Adapter / 3
Pattern Structure – Object Adapter:
– Relies on object composition
adaptee
13
Adapter / 4Adapter / 4
Code / 1:
public class Test{
public static void main( String arg[] ){
try{ Adapter adapter = new
Adapter();adapter.request(); }
catch( Exception e ){ e.printStackTrace(); }
}}
http://www.vico.org/pages/PatronsDisseny/Pattern%20Adapter%20Class/
14
Adapter / 5Adapter / 5
Code / 2:
// Defines the domain specific interface that Client uses
public interface Target{
void request();}
// Adapts the interface of Adaptee to the Target interface
public class Adapter extends Adaptee implements Target
{public void request(){ specificRequest(); }
}
15
Adapter / 6Adapter / 6
Code / 3:
// Defines an existing interface that needs adapting
public class Adaptee{
public void specificRequest(){}
}
16
Adapter / 7Adapter / 7
Example / 1:
Consider a plug-in architecture:
– We have an existing plug-in PluginX for one software (e.g., FirstBrowser)
– We have similar software (e.g., SecondBrowser) with a different plug-in interface
– We want to use the PluginX as part of the SecondBrowser without re-writing it
Courtesy of: Ali Razavi
17
Adapter / 8Adapter / 8
Example / 2:
FirstBrowser
<<Interface>>
FirstBrowserPlugin
StartPlugin():void
PluginX
<<Interface>>
SecondBrowserPlugin
InitPlugin():void
Start():void
SecondBrowser
XAdapter
StartPlugin():void
InitPlugin();
Start();
+
+
18
AgendaAgenda
Design Patterns
Factory Method
Adapter
Bridge
o Command
o State
o Proxy
Summary and References
19
Bridge / 1Bridge / 1
Intent: The decoupling of an abstraction from its implementation in order to vary both independently
Also Known As: Handle / Body
Applicability:
– To avoid permanent binding between an abstraction and its implementation
– Both the abstraction and its implementation should be extensible through subclasses
– The clients should not be impacted by changes in the abstraction implementation
– The client is hidden from the fact that multiple objects share the same implementation
21
Bridge / 3Bridge / 3
Code / 1:
public class Test{
public static void main( String arg[] ){
try{ Abstraction abstraction = new
RefinedAbstraction();Implementor implementor = new
ConcreteImplementorB();
abstraction.setImplementor( implementor );abstraction.operation(); }
catch( Exception e ){ e.printStackTrace(); }
}}
22
Bridge / 4Bridge / 4
Code / 2:
// Extends the interface defined by Abstraction
public class RefinedAbstraction extends Abstraction{
public void operation(){ super.operation(); }
}
23
Bridge / 5Bridge / 5
Code / 3:
// Defines the interface for implementation classes that does not have to exactly correspond to Abstraction's interface. Usually the Implementor interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives
public interface Implementor{
void operation();}
24
Bridge / 6Bridge / 6
Code / 4:
// Implements the Implementor interface and defines its conrete implementation
public class ConcreteImplementorB implements Implementor
{ public void operation(){ } }
// Implements the Implementor interface and defines its concrete implementation
public class ConcreteImplementorA implements Implementor
{ public void operation(){ } }
25
Bridge / 7Bridge / 7
Code / 5:
// Defines the abstraction's interface, and maintains a reference to an object of type Implementor
public class Abstraction{
private Implementor implementor;public void setImplementor( Implementor implementor ){ this.implementor = implementor; }public Implementor getImplementor(){ return implementor; }public void operation(){ implementor.operation(); }
}
http://www.vico.org/pages/PatronsDisseny/Pattern%20Bridge/
26
Bridge / 8Bridge / 8
Example:
The JDBCAdapter class adapts information in a database table to appear in Swing Jtable component.
27
Bridge / 9Bridge / 9 Example Code / 1:
– Common use: Overall design of an application that uses drivers. Application development is separated from the development of the drivers that implement the application's abstract operations
– The JDBC architecture decouples an abstraction from its implementation so that the two can vary
// To use a JDBC driver, you load it, connect to a database, and create a Statement object
Class.forName(driverName); Connection c = DriverManager.getConnection(url,
user, passwd); Statement s = c.createStatement();
28
Bridge / 10Bridge / 10
Example Code / 2:
// The variable s is a Statement object, capable of issuing SQL queries that return result sets.
ResultSet r = s.executeQuery( "select name, apogee from firework");
while(r.next()) {
String name = r.getString("name"); int apogee = r.getInt("apogee");System.out.println(name + ", " + apogee);
}
http://www.awprofessional.com/articles/article.asp?p=29302&rl=1
29
AgendaAgenda
Design Patterns
Factory Method
Adapter
Bridge
Command
o State
o Proxy
Summary and References
30
Command / 1Command / 1
Intent: A request is encapsulated as an object, allowing the parameterization of clients with different requests, queuing or logging of requests, and supporting undoable operations
Also Known As: Action, Transaction
Applicability:
– Parameterization of objects with an action to perform
– Specification, queuing, and execution of requests at different times, where a command object can have a lifetime independent of original request
– Support of logging changes that can be reapplied if the system crashes
– A system of high-level operations built on primitives operations
32
Command / 3Command / 3
Code / 1:
public class Test{
public static void main( String arg[] ){ try
{ Client client = new Client();Command command =
client.setup();command.execute(); }
catch( Exception e ){ e.printStackTrace(); }
}}
http://www.vico.org/pages/PatronsDisseny/Pattern%20Command/
33
Command / 4Command / 4
Code / 2:
// Knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver
public interface Receiver{ void action();}
// Implementation of the Receiver interface
public class ConcreteReceiver implements Receiver{ public void action()
{ }}
34
Command / 5Command / 5
Code / 3:
// Defines a binding between a Receiver object and an action. Implements Execute by invoking the corresponding operation on Receiver
public class ConcreteCommand implements Command{
private Receiver receiver;public void setReceiver( Receiver receiver ){ this.receiver = receiver; }public Receiver getReceiver(){ return receiver; }public void execute(){ receiver.action(); }
}
35
Command / 6Command / 6
Code / 4:
// Declares an interface for executing an operation
public interface Command{ void setReceiver( Receiver receiver );
Receiver getReceiver(); void execute(); }
// Creates a ConcreteCommand object & specifies its receiver
public class Client{ public Command setup()
{ Command command = new ConcreteCommand();Receiver receiver = new ConcreteReceiver();command.setReceiver( receiver );
// Return the command so that the Invoker may use itreturn command; } }
36
AgendaAgenda
Design Patterns
Factory Method
Adapter
Bridge
Command
State
o Proxy
Summary and References
37
State / 1State / 1
Intent: When the internal state of an object changes it is allowed to alter its behaviour. The object appears to change its class
Also Known As: Objects for States
Applicability:
– An object must undergo change in its behaviour at run-time depending on its state
– Operations that have large, multipart conditional statements that depend on the object’s state
39
State / 3State / 3 Code / 1:
public class Test{ public static void main( String arg[] )
{ try { State state = new ConcreteStateA();
Context context = new Context();context.setState( state );context.request(); }
catch( Exception e ){ e.printStackTrace(); } } }
// Defines an interface for encapsulating the behavior associated with a particular state of the Context
public interface State{ void handle(); }
http://www.vico.org/pages/PatronsDisseny/Pattern%20State/
40
State / 4State / 4
Code / 2:
// Defines the interface of interest to clients. Maintains an instance of a ConcreteState subclass that defines the current state
public class Context{ private State state;
public void setState( State state ){ this.state = state; }public State getState(){ return state; }public void request(){ state.handle(); }}
41
State / 5State / 5
Code / 3:
// Each subclass implements a behavior associated with a state of the Context
public class ConcreteStateB implements State{ public void handle()
{ }}
// Each subclass implements a behavior associated with a state of the Context
public class ConcreteStateA implements State{ public void handle()
{ } }
42
AgendaAgenda
Design Patterns
Factory Method
Adapter
Bridge
Command
State
Proxy
Summary and References
43
Proxy / 1Proxy / 1
Intent: “Provide a surrogate or placeholder for another object to control access to it”
Also Known As: Surrogate
Applicability:
– Need for a more versatile or sophisticated reference to an object than a simple pointer
• Remote, virtual, protection proxies
• Smart proxy
Design Patterns – Gamma et. al.
45
Proxy / 3Proxy / 3 Code / 1:
public class Test{ public static void main( String arg[] )
{ try { Subject real = new RealSubject();Proxy proxy = new Proxy();proxy.setRealSubject( real );proxy.request(); }
catch( Exception e ){ e.printStackTrace(); } } }
// Defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected
public interface Subject{ void request(); }
46
Proxy / 4Proxy / 4
Code / 2:
// Defines the real object that the proxy represents
public class RealSubject implements Subject{ public void request()
{ // Do something based on the interface }}
// Maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same. Provides an interface identical to Subject's so that a proxy can by substituted for the real subject
http://www.vico.org/pages/PatronsDisseny/Pattern%20Proxy/
47
Proxy / 5Proxy / 5
Code / 3:
public class Proxy implements Subject{ private Subject realSubject;
public void setRealSubject( Subject subject ){ realSubject = subject; }public Subject getRealSubject(){ // This may not be possible if the proxy is communicating over a network
return realSubject; }public void request(){ // This is very simplified. This could actually be a call to a different run-time environment locally, a machine over a TCP socket, or something completely different.
realSubject.request(); }}
48
AgendaAgenda
Design Patterns
Factory Method
Adapter
Bridge
Command
State
Proxy
Summary and References
49
Tutorial SummaryTutorial Summary
In this tutorial, we have presented the following design patterns:
– Factory Method, Adapter, Bridge, Command, State, and Proxy
We have demonstrated intent, applicability, and illustrative examples for each pattern
We have also discussed pointers for further study