More Related Content
Similar to Design Patterns - Part 2 of 2 (20)
Design Patterns - Part 2 of 2
- 1. Design Patterns – Part 2 sample for a picture in the title slide Savio Sebastian, Patterns Component Team January 11, 2008
- 2. Agenda sample for a picture in the divider slide Design Principles Creational Patterns 2.1. Builder Pattern 2.2. Lazy Initialization Pattern 2.3. Object Pool Structural Patterns 3.1. Composite Pattern 3.2. Proxy Pattern Behavioral Patterns 4.1. Strategy Pattern 4.2. State Pattern Conclusion © SAP 2007 / Page 2
- 3. © SAP 2007 / Page 3 Design Principles OO Design Principles
- 4. 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
- 5. © SAP 2007 / Page 5 Creational Patterns Builder Pattern Lazy Initialization Pattern Object Pool
- 6. 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
- 8. 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
- 9. 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
- 10. 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
- 11. © SAP 2007 / Page 11 Structural Patterns Composite Pattern Proxy Pattern
- 12. 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
- 14. 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
- 16. 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
- 17. 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
- 18. 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
- 20. 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
- 21. © SAP 2007 / Page 21 Behavioral Patterns Strategy Pattern State Pattern Template Method
- 22. 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
- 23. Strategy Pattern ExampleInterface FlyBehavior and it’s implementations public interface FlyBehavior{ public void fly(); } public class FlyNoWayimplements 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 FlyWithWingsimplements FlyBehavior { public void fly() { System.out.println("I'm flying!!"); } } © SAP 2007 / Page 23
- 24. Strategy Pattern ExampleDuck.java which encapsulates FlyBehavior public abstract class Duck { FlyBehaviorflyBehavior; public Duck() { } public void setFlyBehavior (FlyBehaviorfb) { 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
- 25. 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
- 27. 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
- 28. State Pattern ExampleState.java public interface State { public void insertQuarter(); public void ejectQuarter(); public void turnCrank(); public void dispense(); } © SAP 2007 / Page 28
- 29. State PatternGumballMachine.java public class GumballMachine { State soldOutState; State noQuarterState; State hasQuarterState; State soldState; State state = soldOutState; int count = 0; public GumballMachine(intnumberGumballs) { 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
- 30. State PatternNoQuarterState.java public class NoQuarterState implements State { GumballMachinegumballMachine; public NoQuarterState(GumballMachinegumballMachine) { 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
- 31. State PatternGumballMachineTestDrive.java public class GumballMachineTestDrive { public static void main(String[] args) { GumballMachinegumballMachine = 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
- 33. © SAP 2007 / Page 33 Conclusion Final Recap When to Use
- 41. 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
- 42. © SAP 2007 / Page 42 Definition and halftone values of colors SAP Blue SAP Gold SAP Dark Gray SAP Gray SAP Light Gray RGB 4/53/123 RGB 240/171/0 RGB 102/102/102 RGB 153/153/153 RGB 204/204/204 Primary color palette 100% Dove Petrol Violet/Mauve Warm Red Warm Green RGB 68/105/125 RGB 21/101/112 RGB 85/118/48 RGB 119/74/57 RGB 100/68/89 Secondary color palette100% RGB 96/127/143 RGB 98/146/147 RGB 110/138/79 RGB 140/101/87 RGB 123/96/114 85% RGB 125/150/164 RGB 127/166/167 RGB 136/160/111 RGB 161/129/118 RGB 147/125/139 70% RGB 152/173/183 RGB 154/185/185 RGB 162/180/141 RGB 181/156/147 RGB 170/152/164 55% RGB 180/195/203 RGB 181/204/204 RGB 187/200/172 RGB 201/183/176 RGB 193/180/189 40% Cool Green Ocher Warning Red Cool Red RGB 158/48/57 RGB 73/108/96 RGB 129/110/44 RGB 132/76/84 Tertiary color palette100% RGB 101/129/120 RGB 148/132/75 RGB 150/103/110 85% RGB 129/152/144 RGB 167/154/108 RGB 169/130/136 70% RGB 156/174/168 RGB 186/176/139 RGB 188/157/162 55% RGB 183/196/191 RGB 205/197/171 RGB 206/183/187 40%