Upload
savio-sebastian
View
1.812
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Creational Patterns - Builder Pattern - Lazy Initialization Pattern - Object Pool Structural Patterns - Composite Pattern - Proxy Pattern Behavioral Patterns - Strategy Pattern - State Pattern
Citation preview
Design Patterns – Part 2
Savio Sebastian, Patterns Component TeamJanuary 11, 2008
sample for a
picture in the title
slide
© SAP 2007 / Page 2
1. Design Principles
2. Creational Patterns2.1. Builder Pattern2.2. Lazy Initialization Pattern2.3. Object Pool
3. Structural Patterns3.1. Composite Pattern3.2. Proxy Pattern
4. Behavioral Patterns4.1. Strategy Pattern4.2. State Pattern
5. Conclusion
Agenda
sample for a
picture in the
divider slide
© SAP 2007 / Page 3
OO Design Principles
Design Principles
OO Design Principles
Encapsulate what varies (eg: Strategy, State Patterns) Favor composition over inheritance (eg: State, Strategy Patterns) Strive for loosely coupled designs between objects that interact (eg: Observer Pattern) Classes should be open for extension but closed for modification (eg: Factory Method) Depend on abstractions. Do not depend on concrete classes (eg: Factory Method)
© SAP 2007 / Page 4
© SAP 2007 / Page 5
Builder PatternLazy Initialization PatternObject Pool
Creational Patterns
Builder Pattern Defined
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
When to use: When you’re building an object in steps, such that each step can be added on to each other to
construct the final product
Eg:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "(local)";
builder.InitialCatalog = "Product";
builder.IntegratedSecurity = true;
SqlConnection connection = new SqlConnection(builder.ToString());
© SAP 2007 / Page 6
Class diagram for Builder Pattern
© SAP 2007 / Page 7
Lazy Initialization
Lazy Initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed
It’s a combination of ideas from factory and singleton design patterns: Objects can be created in synchronized method block Use a map to hold objects which have different parameters, if necessary Instantiate the object the first time it is requested for
When to Use It is useful when resources are to be conserved
© SAP 2007 / Page 8
Code Example – Lazy Initialization Pattern
public class Fruit
{
private static final Map<String,Fruit>types = new HashMap<String,Fruit>();
private final String type;
private Fruit(String type) {
this.type = type;
}
public static synchronized Fruit getFruit(String type) {
Fruit f = types.get(type); // get the instance for that type
if (f == null) {
f = new Fruit(type); // lazy initialization
types.put(type,f);
}
return f;
}
}
© SAP 2007 / Page 9
Object Pool – defined
Object Pool is a set of initialised objects that are kept ready to use, rather than allocated and destroyed on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object, it returns it to the pool, rather than destroying it.
The object needs to be re-set after the client has finished using the object. The resetting needs to be done by the Pool manager and not the client. If not it leads to cesspools.
Inadequate resetting can lead to information leak
When to use: When initialization of objects is costly, eg: database connection pools
© SAP 2007 / Page 10
© SAP 2007 / Page 11
Composite PatternProxy Pattern
Structural Patterns
Composite Pattern
Composite allows a group of objects to be treated in the same way as a single instance of an object.
The intent of Composite is to compose objects into tree structures to represent part-whole hierarchies.
Motivation Differentiating between leaf and branch nodes require complex logic and is error prone Solution: interface which treats complex and primitive objects uniformly
When to Use Use when clients need not differentiate between branch and leaf node
Eg: Menu structure – one method “display()” should be able to be called on a branch node which in turn delegates it to it’s leaves/branches under it instead of having the client to iterate through the structure
© SAP 2007 / Page 12
Composite Pattern Class Diagram
© SAP 2007 / Page 13
Component – Leaf – Composite
Component is the abstraction for all components, including composite ones declares the interface for objects in the composition implements default behavior for the interface common to all classes, as appropriate declares an interface for accessing and managing its child components
Leaf represents leaf objects in the composition implements all Component methods
Composite represents a composite Component (component having children) implements methods to manipulate children implements all Component methods, generally by delegating them to its children
© SAP 2007 / Page 14
Example
Need to look at the source code here
© SAP 2007 / Page 15
Proxy Pattern
A representative object controls access to another object which may be remote, expensive to create, etc
When to use: Remote proxy: Provides a reference to an object located in a different address space on the
same or different machine. Virtual proxy: Allows the creation of a memory intensive object on demand. The object will
not be created until it is really needed. Protection (access) proxy: Provides different clients with different levels of access to a
target object.
© SAP 2007 / Page 16
Proxy Pattern – ExampleImage.java & Resource hungry RealImage.java
interface Image {
public void displayImage();
}
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadImageFromDisk();
}
private void loadImageFromDisk() {
// Potentially expensive operation
}
public void displayImage() { System.out.println("Displaying "+filename); }
}
© SAP 2007 / Page 17
Proxy Pattern – ExampleProxyImage.java & ProxyExample.java
class ProxyImage implements Image {
private String filename;
private Image image;
public ProxyImage(String filename) {
this.filename = filename;
}
public void displayImage() {
if (image == null) {
image = new RealImage(filename);
// load only on demand
}
image.displayImage();
}
}
class ProxyExample {
public static void main(String[] args) {
ArrayList<Image> images = new ArrayList<Image>();
images.add( new ProxyImage("HiRes_10MB_Photo1") );
images.add( new ProxyImage("HiRes_10MB_Photo2") );
images.add( new ProxyImage("HiRes_10MB_Photo3") );
images.get(0).displayImage(); // loading necessary
images.get(1).displayImage(); // loading necessary
images.get(0).displayImage();
// no loading necessary; already done
//the third image will never be loaded time saved!
}
}
© SAP 2007 / Page 18
Proxy Pattern Class Diagram
© SAP 2007 / Page 19
Proxy and Decorator PatternsSimilar yet Dissimilar
Both have similar class diagrams But they have very different functionality Proxy is used for Representing Subjects Decorator is used to Add Responsibility to the subjects
© SAP 2007 / Page 20
© SAP 2007 / Page 21
Strategy PatternState PatternTemplate Method
Behavioral Patterns
Strategy Pattern
Define a family of algorithms, encapsulate each one, and make them interchangable
Algorithms may be selected or changed at runtime
When to use: Situations where it is necessary to dynamically swap the algorithms used in an application
© SAP 2007 / Page 22
Strategy Pattern ExampleInterface FlyBehavior and it’s implementations
public interface FlyBehavior {
public void fly();
}
public class FlyNoWay implements FlyBehavior {
public void fly() {
System.out.println("I can't fly");
}
}
public class FlyRocketPowered implements FlyBehavior {
public void fly() {
System.out.println("I'm flying with a rocket");
}
}
public class FlyWithWings implements
FlyBehavior {
public void fly() {
System.out.println("I'm flying!!");
}
}
© SAP 2007 / Page 23
Strategy Pattern ExampleDuck.java which encapsulates FlyBehavior
public abstract class Duck {
FlyBehavior flyBehavior;
public Duck() {
}
public void setFlyBehavior (FlyBehavior fb) {
flyBehavior = fb;
}
abstract void display();
public void performFly() {
flyBehavior.fly();
}
public void swim() {
System.out.println("All ducks float, even decoys!");
}
}
© SAP 2007 / Page 24
Strategy Pattern ExampleRubberDuck.java & Simulator
public class RubberDuck extends Duck {
public RubberDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Squeak();
}
public void display() {
System.out.println("I'm a rubber duckie");
}
}
public class MiniDuckSimulator1 {
public static void main(String[] args) {
Duck model = new RubberDuck();
model.performFly();
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
}
}
© SAP 2007 / Page 25
Strategy Pattern Class Diagram
© SAP 2007 / Page 26
State Pattern
Allow an object to alter its behavior when its internal state changes.
When to use: Situations where the object behavior changes depending on the state it is at
Similar to Strategy Pattern: Intent is different – State Pattern is built around discrete states, and the context objects
change state over time according to some well defined state transitions Changing behavior is built into the scheme for State Pattern Strategy Pattern does not encourage its objects to have well-defined set of transitions
between states
© SAP 2007 / Page 27
State Pattern ExampleState.java
public interface State {
public void insertQuarter();
public void ejectQuarter();
public void turnCrank();
public void dispense();
}
© SAP 2007 / Page 28
State PatternGumballMachine.java
public class GumballMachine {
State soldOutState;
State noQuarterState;
State hasQuarterState;
State soldState;
State state = soldOutState;
int count = 0;
public GumballMachine(int numberGumballs) {
soldOutState = new SoldOutState(this);
noQuarterState = new NoQuarterState(this);
hasQuarterState = new HasQuarterState(this);
soldState = new SoldState(this);
this.count = numberGumballs;
if (numberGumballs > 0) {
state = noQuarterState;
}
}
public void insertQuarter() {
state.insertQuarter();
}
public void ejectQuarter() {
state.ejectQuarter();
}
public void turnCrank() {
state.turnCrank();
state.dispense();
}
void setState(State state) {
this.state = state;
}
void refill(int count) {
this.count = count;
state = noQuarterState;
}
public State getState() {
return state;
}
public State getSoldOutState() {
return soldOutState;
}
public State getNoQuarterState() {
return noQuarterState;
}
public State getHasQuarterState() {
return hasQuarterState;
}
public State getSoldState() {
return soldState;
}
}
© SAP 2007 / Page 29
State Pattern NoQuarterState.java
public class NoQuarterState implements State {
GumballMachine gumballMachine;
public NoQuarterState(GumballMachine gumballMachine) {
this.gumballMachine = gumballMachine;
}
public void insertQuarter() {
System.out.println("You inserted a quarter");
gumballMachine.setState( gumballMachine.getHasQuarterState() ) ;
}
public void ejectQuarter() {
System.out.println("You haven't inserted a quarter");
}
public void turnCrank() {
System.out.println("You turned, but there's no quarter");
}
public void dispense() {
System.out.println("You need to pay first");
}
public String toString() {
return "waiting for quarter";
}
}
© SAP 2007 / Page 30
State Pattern GumballMachineTestDrive.java
public class GumballMachineTestDrive {
public static void main(String[] args) {
GumballMachine gumballMachine = new GumballMachine(5);
System.out.println(gumballMachine);
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
System.out.println(gumballMachine);
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
System.out.println(gumballMachine);
}
}
© SAP 2007 / Page 31
State Pattern Class Diagram
© SAP 2007 / Page 32
Context
request()… state.handle()
State
handle()
ConcreteStateA
handle()
ConcreteStateB
handle()
© SAP 2007 / Page 33
Final RecapWhen to Use
Conclusion
Quick Reference: Different Types of Creational Patterns
Name Description
Abstract factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Factory method
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Builder Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Lazy initialization
Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
Singleton Ensure a class only has one instance, and provide a global point of access to it.
Object Pool Avoid expensive acquisition and release of resources by recycling objects that are no longer in use
© SAP 2007 / Page 34
Quick Reference: Different Types of Structural Patterns
Name Description
Adapter Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Composite Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Decorator Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Façade 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.
Proxy Provide a surrogate or placeholder for another object to control access to it.
© SAP 2007 / Page 35
Quick Reference: Different Types of Behavioral Patterns
Name Description
Command Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Observer Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
State Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Strategy Define a family of algorithms, encapsulate each one, and make them interchangable. Strategy lets the algorithm vary independently from clients that use it.
© SAP 2007 / Page 36
Quick Reference: When to Use – Creational Patterns
Name Description
Abstract factory
When there are families of behavior/themes which you can group and encapsulate into the class. Internally use Factory Method for getting the appropriate behavior implementation
Factory method
Use it when you have different flavors with specialized methods but still some standard methods shared by all the different flavors.
Builder When you’re building an object in steps, such that each step can be added on to each other to construct the final product
Lazy initialization
It is useful when resources are to be conserved
Singleton Used for objects that handle logging, caches, registry settings, etc
Object Pool When initialization of objects is costly, eg: database connection pools
© SAP 2007 / Page 37
Quick Reference: When to Use – Structural Patterns
Name Description
Adapter When you need to adapt the functionality of one to another, eg: your software with a third party interface
Composite Use when clients need not differentiate between branch and leaf node
Decorator When you need to add flavors onto a concrete implementation – where the concrete implementation can exist and be used by itself, or have any number of Decorations (responsibilities) loaded on top of it.
Façade To provide a simple interface to an otherwise complex implementation
Proxy Remote proxy: Provides a reference to an object located in a different address space on the same or different machine. Virtual proxy: Allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.Protection (access) proxy: Provides different clients with different levels of access to a target object.
© SAP 2007 / Page 38
Quick Reference: When to Use – Behavioral Patterns
Name Description
Command Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Observer Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
State Situations where the object behavior changes depending on the state it is at
Strategy Situations where it is necessary to dynamically swap the algorithms used in an application
© SAP 2007 / Page 39
© SAP 2007 / Page 40
Thank you!
References
Head First Design Patterns Eric & Elizabeth Freeman with Kathy Sierra & Bert Bates
Wikipedia http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29
YouTube http://www.youtube.com/codingkriggs
© SAP 2007 / Page 41