Design Patterns - Part 2 of 2

2,378 views

Published on

Creational Patterns
- Builder Pattern
- Lazy Initialization Pattern
- Object Pool


Structural Patterns
- Composite Pattern
- Proxy Pattern


Behavioral Patterns
- Strategy Pattern
- State Pattern

Published in: Education
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,378
On SlideShare
0
From Embeds
0
Number of Embeds
13
Actions
Shares
0
Downloads
180
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Design Patterns - Part 2 of 2

  1. 1. Design Patterns – Part 2<br />sample for a picture in the title slide<br />Savio Sebastian, Patterns Component Team<br />January 11, 2008<br />
  2. 2. Agenda<br />sample for a picture in the divider slide<br />Design Principles<br />Creational Patterns<br />2.1. Builder Pattern<br />2.2. Lazy Initialization Pattern<br />2.3. Object Pool<br /> Structural Patterns<br />3.1. Composite Pattern<br />3.2. Proxy Pattern<br /> Behavioral Patterns<br />4.1. Strategy Pattern<br />4.2. State Pattern<br />Conclusion<br />© SAP 2007 / Page 2<br />
  3. 3. © SAP 2007 / Page 3<br />Design Principles<br />OO Design Principles<br />
  4. 4. OO Design Principles<br />Encapsulate what varies (eg: Strategy, State Patterns)<br />Favor composition over inheritance (eg: State, Strategy Patterns)<br />Strive for loosely coupled designs between objects that interact (eg: Observer Pattern)<br />Classes should be open for extension but closed for modification (eg: Factory Method)<br />Depend on abstractions. Do not depend on concrete classes (eg: Factory Method)<br />© SAP 2007 / Page 4<br />
  5. 5. © SAP 2007 / Page 5<br />Creational Patterns<br />Builder Pattern<br />Lazy Initialization Pattern<br />Object Pool<br />
  6. 6. Builder Pattern Defined<br />Separate the construction of a complex object from its representation so that the same construction process can create different representations.<br />When to use:<br />When you’re building an object in steps, such that each step can be added on to each other to construct the final product<br />Eg:<br />SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();<br />builder.DataSource = "(local)"; <br />builder.InitialCatalog = "Product"; <br />builder.IntegratedSecurity = true; <br />SqlConnection connection = new SqlConnection(builder.ToString());<br />© SAP 2007 / Page 6<br />
  7. 7. Class diagram for Builder Pattern<br />© SAP 2007 / Page 7<br />
  8. 8. Lazy Initialization<br />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<br />It’s a combination of ideas from factory and singleton design patterns:<br />Objects can be created in synchronized method block<br />Use a map to hold objects which have different parameters, if necessary<br />Instantiate the object the first time it is requested for<br />When to Use<br />It is useful when resources are to be conserved<br />© SAP 2007 / Page 8<br />
  9. 9. Code Example – Lazy Initialization Pattern<br />public class Fruit<br />{<br /> private static final Map<String,Fruit>types = new HashMap<String,Fruit>();<br /> private final String type; <br /> private Fruit(String type) {<br />this.type = type;<br /> } <br /> public static synchronized Fruit getFruit(String type) {<br /> Fruit f = types.get(type); // get the instance for that type<br /> if (f == null) {<br />f = new Fruit(type); // lazy initialization<br />types.put(type,f);<br /> } <br /> return f;<br /> }<br />}<br />© SAP 2007 / Page 9<br />
  10. 10. Object Pool – defined<br />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. <br />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.<br />Inadequate resetting can lead to information leak<br />When to use:<br />When initialization of objects is costly, eg: database connection pools<br />© SAP 2007 / Page 10<br />
  11. 11. © SAP 2007 / Page 11<br />Structural Patterns<br />Composite Pattern<br />Proxy Pattern<br />
  12. 12. Composite Pattern<br />Composite allows a group of objects to be treated in the same way as a single instance of an object. <br />The intent of Composite is to compose objects into tree structures to represent part-whole hierarchies.<br />Motivation<br />Differentiating between leaf and branch nodes require complex logic and is error prone<br />Solution: interface which treats complex and primitive objects uniformly<br />When to Use<br />Use when clients need not differentiate between branch and leaf node<br />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<br />© SAP 2007 / Page 12<br />
  13. 13. Composite Pattern Class Diagram<br />© SAP 2007 / Page 13<br />
  14. 14. Component – Leaf – Composite<br />Component<br />is the abstraction for all components, including composite ones <br />declares the interface for objects in the composition <br />implements default behavior for the interface common to all classes, as appropriate <br />declares an interface for accessing and managing its child components <br />Leaf<br />represents leaf objects in the composition <br />implements all Component methods <br />Composite<br />represents a composite Component (component having children) <br />implements methods to manipulate children <br />implements all Component methods, generally by delegating them to its children <br />© SAP 2007 / Page 14<br />
  15. 15. Example<br />Need to look at the source code here<br />© SAP 2007 / Page 15<br />
  16. 16. Proxy Pattern<br />A representative object controls access to another object which may be remote, expensive to create, etc<br />When to use:<br />Remote proxy: Provides a reference to an object located in a different address space on the same or different machine. <br />Virtual proxy: Allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.<br />Protection (access) proxy: Provides different clients with different levels of access to a target object. <br />© SAP 2007 / Page 16<br />
  17. 17. Proxy Pattern – ExampleImage.java & Resource hungry RealImage.java<br />interface Image {<br /> public void displayImage();<br />}<br />class RealImage implements Image {<br /> private String filename;<br /> public RealImage(String filename) { <br />this.filename = filename;<br />loadImageFromDisk();<br /> } <br /> private void loadImageFromDisk() {<br /> // Potentially expensive operation<br /> } <br /> public void displayImage() { System.out.println("Displaying "+filename); }<br />}<br />© SAP 2007 / Page 17<br />
  18. 18. Proxy Pattern – ExampleProxyImage.java & ProxyExample.java<br />class ProxyImage implements Image {<br /> private String filename;<br /> private Image image;<br /> public ProxyImage(String filename) { <br />this.filename= filename; <br /> }<br /> public void displayImage() {<br /> if (image == null) {<br /> image = new RealImage(filename); <br /> // load only on demand<br /> }<br />image.displayImage();<br /> }<br />}<br />class ProxyExample {<br /> public static void main(String[] args) {<br />ArrayList<Image> images = new ArrayList<Image>();<br />images.add( new ProxyImage("HiRes_10MB_Photo1") );<br />images.add( new ProxyImage("HiRes_10MB_Photo2") );<br />images.add( new ProxyImage("HiRes_10MB_Photo3") );<br />images.get(0).displayImage(); // loading necessary<br />images.get(1).displayImage(); // loading necessary<br />images.get(0).displayImage(); <br /> // no loading necessary; already done<br />//the third image will never be loaded time saved!<br /> }<br />}<br />© SAP 2007 / Page 18<br />
  19. 19. Proxy Pattern Class Diagram<br />© SAP 2007 / Page 19<br />
  20. 20. Proxy and Decorator PatternsSimilar yet Dissimilar<br />Both have similar class diagrams<br />But they have very different functionality<br />Proxy is used for Representing Subjects<br />Decorator is used to Add Responsibility to the subjects<br />© SAP 2007 / Page 20<br />
  21. 21. © SAP 2007 / Page 21<br />Behavioral Patterns<br />Strategy Pattern<br />State Pattern<br />Template Method<br />
  22. 22. Strategy Pattern<br />Define a family of algorithms, encapsulate each one, and make them interchangable<br />Algorithms may be selected or changed at runtime<br />When to use:<br />Situations where it is necessary to dynamically swap the algorithms used in an application<br />© SAP 2007 / Page 22<br />
  23. 23. Strategy Pattern ExampleInterface FlyBehavior and it’s implementations<br />public interface FlyBehavior{<br /> public void fly();<br />}<br />public class FlyNoWayimplements FlyBehavior {<br /> public void fly() {<br />System.out.println("I can't fly");<br /> }<br />}<br />public class FlyRocketPowered implements FlyBehavior {<br /> public void fly() {<br />System.out.println("I'm flying with a rocket");<br /> }<br />}<br />public class FlyWithWingsimplements FlyBehavior {<br /> public void fly() {<br />System.out.println("I'm flying!!");<br /> }<br />}<br />© SAP 2007 / Page 23<br />
  24. 24. Strategy Pattern ExampleDuck.java which encapsulates FlyBehavior<br />public abstract class Duck {<br />FlyBehaviorflyBehavior; <br /> public Duck() {<br /> } <br /> public void setFlyBehavior (FlyBehaviorfb) {<br />flyBehavior = fb;<br /> } <br /> abstract void display();<br /> public void performFly() {<br /> flyBehavior.fly();<br /> } <br /> public void swim() {<br />System.out.println("All ducks float, even decoys!");<br /> }<br />}<br />© SAP 2007 / Page 24<br />
  25. 25. Strategy Pattern ExampleRubberDuck.java & Simulator<br />public class RubberDuck extends Duck { <br /> public RubberDuck() {<br />flyBehavior = new FlyNoWay();<br />quackBehavior = new Squeak();<br /> }<br /> public void display() {<br />System.out.println("I'm a rubber duckie");<br /> }<br />}<br />public class MiniDuckSimulator1 { <br /> public static void main(String[] args) {<br /> Duck model = new RubberDuck();<br />model.performFly();<br />model.setFlyBehavior(new FlyRocketPowered());<br />model.performFly();<br /> }<br />}<br />© SAP 2007 / Page 25<br />
  26. 26. Strategy Pattern Class Diagram<br />© SAP 2007 / Page 26<br />
  27. 27. State Pattern<br />Allow an object to alter its behavior when its internal state changes.<br />When to use:<br />Situations where the object behavior changes depending on the state it is at<br />Similar to Strategy Pattern:<br />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<br />Changing behavior is built into the scheme for State Pattern<br />Strategy Pattern does not encourage its objects to have well-defined set of transitions between states<br />© SAP 2007 / Page 27<br />
  28. 28. State Pattern ExampleState.java<br />public interface State { <br /> public void insertQuarter();<br /> public void ejectQuarter();<br /> public void turnCrank();<br /> public void dispense();<br />}<br />© SAP 2007 / Page 28<br />
  29. 29. State PatternGumballMachine.java<br />public class GumballMachine {<br />State soldOutState;<br /> State noQuarterState;<br /> State hasQuarterState;<br /> State soldState;<br /> State state = soldOutState;<br />int count = 0;<br /> public GumballMachine(intnumberGumballs) {<br />soldOutState = new SoldOutState(this);<br />noQuarterState = new NoQuarterState(this);<br />hasQuarterState = new HasQuarterState(this);<br />soldState = new SoldState(this);<br />this.count = numberGumballs;<br /> if (numberGumballs > 0) {<br /> state = noQuarterState;<br /> } <br /> }<br /> public void insertQuarter() {<br />state.insertQuarter();<br /> }<br /> public void ejectQuarter() {<br />state.ejectQuarter();<br /> }<br /> public void turnCrank() {<br />state.turnCrank();<br />state.dispense();<br /> }<br /> void setState(State state) {<br />this.state = state;<br /> }<br />void refill(int count) {<br />this.count = count;<br /> state = noQuarterState;<br /> }<br /> public State getState() {<br /> return state;<br /> }<br /> public State getSoldOutState() {<br /> return soldOutState;<br /> }<br /> public State getNoQuarterState() {<br /> return noQuarterState;<br /> }<br /> public State getHasQuarterState() {<br /> return hasQuarterState;<br /> }<br /> public State getSoldState() {<br /> return soldState;<br /> }<br />}<br />© SAP 2007 / Page 29<br />
  30. 30. State PatternNoQuarterState.java<br />public class NoQuarterState implements State {<br />GumballMachinegumballMachine;<br /> public NoQuarterState(GumballMachinegumballMachine) {<br />this.gumballMachine = gumballMachine;<br /> } <br /> public void insertQuarter() {<br />System.out.println("You inserted a quarter");<br />gumballMachine.setState( gumballMachine.getHasQuarterState() ) ;<br /> } <br /> public void ejectQuarter() {<br />System.out.println("You haven't inserted a quarter");<br /> } <br /> public void turnCrank() {<br />System.out.println("You turned, but there's no quarter");<br /> } <br /> public void dispense() {<br />System.out.println("You need to pay first");<br /> } <br /> public String toString() {<br /> return "waiting for quarter";<br /> }<br />}<br />© SAP 2007 / Page 30<br />
  31. 31. State PatternGumballMachineTestDrive.java<br />public class GumballMachineTestDrive {<br /> public static void main(String[] args) {<br />GumballMachinegumballMachine = new GumballMachine(5);<br />System.out.println(gumballMachine);<br />gumballMachine.insertQuarter();<br />gumballMachine.turnCrank();<br />System.out.println(gumballMachine);<br />gumballMachine.insertQuarter();<br />gumballMachine.turnCrank();<br />gumballMachine.insertQuarter();<br />gumballMachine.turnCrank();<br />System.out.println(gumballMachine);<br /> }<br />}<br />© SAP 2007 / Page 31<br />
  32. 32. State Pattern Class Diagram<br />© SAP 2007 / Page 32<br />
  33. 33. © SAP 2007 / Page 33<br />Conclusion<br />Final Recap<br />When to Use<br />
  34. 34. Quick Reference: Different Types of Creational Patterns<br />© SAP 2007 / Page 34<br />
  35. 35. Quick Reference: Different Types of Structural Patterns<br />© SAP 2007 / Page 35<br />
  36. 36. Quick Reference: Different Types of Behavioral Patterns<br />© SAP 2007 / Page 36<br />
  37. 37. Quick Reference: When to Use – Creational Patterns<br />© SAP 2007 / Page 37<br />
  38. 38. Quick Reference: When to Use – Structural Patterns<br />© SAP 2007 / Page 38<br />
  39. 39. Quick Reference: When to Use – Behavioral Patterns<br />© SAP 2007 / Page 39<br />
  40. 40. © SAP 2007 / Page 40<br />Thank you!<br />
  41. 41. References<br />Head First Design Patterns<br />Eric & Elizabeth Freeman with Kathy Sierra & Bert Bates<br />Wikipedia<br />http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29<br />YouTube<br />http://www.youtube.com/codingkriggs<br />© SAP 2007 / Page 41<br />
  42. 42. © SAP 2007 / Page 42<br />Definition and halftone values of colors<br />SAP Blue<br />SAP Gold<br />SAP Dark Gray<br />SAP Gray<br />SAP Light Gray<br />RGB 4/53/123<br />RGB 240/171/0<br />RGB 102/102/102<br />RGB 153/153/153<br />RGB 204/204/204<br />Primary color palette 100%<br />Dove<br />Petrol<br />Violet/Mauve<br />Warm Red<br />Warm Green<br />RGB 68/105/125<br />RGB 21/101/112<br />RGB 85/118/48<br />RGB 119/74/57<br />RGB 100/68/89<br />Secondary color palette100%<br />RGB 96/127/143<br />RGB 98/146/147<br />RGB 110/138/79<br />RGB 140/101/87<br />RGB 123/96/114<br />85%<br />RGB 125/150/164<br />RGB 127/166/167<br />RGB 136/160/111<br />RGB 161/129/118<br />RGB 147/125/139<br />70%<br />RGB 152/173/183<br />RGB 154/185/185<br />RGB 162/180/141<br />RGB 181/156/147<br />RGB 170/152/164<br />55%<br />RGB 180/195/203<br />RGB 181/204/204<br />RGB 187/200/172<br />RGB 201/183/176<br />RGB 193/180/189<br />40%<br />Cool Green<br />Ocher<br />Warning Red<br />Cool Red<br />RGB 158/48/57<br />RGB 73/108/96<br />RGB 129/110/44<br />RGB 132/76/84<br />Tertiary color palette100%<br />RGB 101/129/120<br />RGB 148/132/75<br />RGB 150/103/110<br />85%<br />RGB 129/152/144<br />RGB 167/154/108<br />RGB 169/130/136<br />70%<br />RGB 156/174/168<br />RGB 186/176/139<br />RGB 188/157/162<br />55%<br />RGB 183/196/191<br />RGB 205/197/171<br />RGB 206/183/187<br />40%<br />

×