Design Patterns<br />sample for a picture in the title slide<br />Savio Sebastian, Patterns Component Team<br />January 11...
Agenda<br />sample for a picture in the divider slide<br />Introduction<br />Creational Patterns<br />2.1.	Singleton Patte...
© SAP 2007 / Page 3<br />Introduction<br />What are Design Patterns?<br />Why do we use them?<br />Types of Design Pattern...
© SAP 2007 / Page 4<br />Introduction to Design Patterns<br />What? <br />Template for writing code<br />Patterns use OO D...
Types of Design Patterns<br />© SAP 2007 / Page 5<br />
What Patterns are NOT<br />Library of Code?<br />Structure for classes to solve certain problems<br />But aren’t Libraries...
Interface == Abstract Class<br />While we study Design Patterns, Abstract Classes and Interface often mean the same thing....
© SAP 2007 / Page 8<br />Creational Patterns<br />Singleton Pattern<br />Factory Method & Abstract Factory<br />
Singleton Pattern – the simplest pattern<br />Ensures a class has only one instance, and provides a global point of access...
Singleton Class Diagram<br />© SAP 2007 / Page 10<br />
Improving performance<br />© SAP 2007 / Page 11<br />
Create Unique Instance Eagerly<br />Code:<br />public class Singleton {<br />	private static Singleton uniqueInstance = ne...
Double-Checked Locking<br />Code:<br />// Danger!  This implementation of Singleton not guaranteed to work prior to Java 5...
Factory Method Pattern<br />Creates objects without specifying the exact class to create<br />Most popular OO Pattern<br /...
Compare Two Implementations<br />© SAP 2007 / Page 15<br />
Compare Dependencies<br />© SAP 2007 / Page 16<br />PizzaStore<br />PizzaStore<br />Pizza<br />NYStyle<br />PeppoPizza<br ...
Explanations<br />© SAP 2007 / Page 17<br />
Class Diagram of Factory Method<br />© SAP 2007 / Page 18<br />
Abstract Factory Pattern<br />Groups object factories that have a common theme<br />Groups together a set of related produ...
Families – Ingredients / Pizzas<br />© SAP 2007 / Page 20<br />
Factory Method versus Abstract Factory<br />© SAP 2007 / Page 21<br />PizzaStore<br />PizzaStore<br />Pizza<br />Ingredien...
Quick Reference: Different Types of Creational Patterns<br />© SAP 2007 / Page 22<br />
© SAP 2007 / Page 23<br />Structural Patterns<br />Adapter Pattern<br />Decorator Pattern<br />Façade Pattern<br />
Adapter Pattern<br />Adapter lets classes work together that couldn't otherwise because of incompatible interfaces<br />© ...
Ducks<br />Target Interface<br />public interface Duck {<br />  public void quack();<br />  public void fly();<br />}<br /...
Turkeys<br />To-Be-Adapted Interface<br />public interface Turkey {<br />  public void gobble();<br />  public void fly();...
Turkey Adapted<br />public class TurkeyAdapter implements Duck {<br />  Turkey turkey; <br />  public TurkeyAdapter(Turkey...
Client Application Test Drive<br />public class DuckTestDrive {<br />  public static void main(String[] args) {<br />Malla...
Adapting Enumerations to Iterators<br />public class EnumerationIterator implements Iterator {<br />  Enumeration enumerat...
Decorator Pattern<br />Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternat...
java.io uses decorator to extend behaviors<br />© SAP 2007 / Page 31<br />
FilterInputStream.java<br />public class FilterInputStream extends InputStream {    <br />  protected volatile InputStream...
Extending java.io  New ClassLowerCaseInputStream.java<br />public class LowerCaseInputStream extends FilterInputStream {<...
LowerCaseInputStream.java Test Drive<br />public class InputTest {<br />  public static void main(String[] args) throws IO...
Remember!<br />Inheritance is one form of extension, but there are other ways to do the same<br />Designs should allow beh...
Decorator and Adapter<br />© SAP 2007 / Page 36<br />
Façade Pattern<br />Facade defines a higher-level interface that makes the sub-system easier to use<br />Do not create des...
Class Diagram for Façade Pattern<br />© SAP 2007 / Page 38<br />
© SAP 2007 / Page 39<br />Behavioral Patterns<br />Command Pattern<br />Observer Pattern<br />
Command Pattern<br />Encapsulate a request as an object, thereby letting you parameterize clients with different requests,...
Home Automation through Command PatternLight.java<br />public class Light {<br />  public Light() {<br />  }<br />  public...
Command.java<br />public interface Command {<br />public void execute();<br />	public void undo();<br />}<br />© SAP 2007 ...
LightOnCommand.java<br />public class LightOnCommand implements Command {<br />Light light;<br />public LightOnCommand(Lig...
LightOffCommand.java<br />public class LightOffCommand implements Command {<br />	Light light;<br />	public LightOffComman...
Test Drive Command Pattern RemoteLoader.java<br />public class RemoteLoader {<br />	public static void main(String[] args)...
Test Drive Façade and Command Pattern Together<br />You need to look at the code now.<br />© SAP 2007 / Page 46<br />
Class Diagram for Command Pattern<br />© SAP 2007 / Page 47<br />
Observer Pattern<br />Define a one-to-many dependency between objects so that when one object changes state, all its depen...
Subject Interface Isubject.java<br />public interface ISubject {<br />	public void registerObserver( IObserver o ) ;<br />...
Observer Interface IObserver.java<br />public interface IObserver {<br />public void notify( int temp , int humidity , int...
Design Principle<br />© SAP 2007 / Page 51<br />The Subject doesn’t care, it will deliver notifications to any object that...
© SAP 2007 / Page 52<br />Thank you!<br />
References<br />Head First Design Patterns<br />Eric & Elizabeth Freeman with Kathy Sierra & Bert Bates<br />Wikipedia<br ...
Upcoming SlideShare
Loading in...5
×

Design Patterns - Part 1 of 2

3,951

Published on

Introduction
Creational Patterns
- Singleton Pattern
- Factory Method and Abstract Factory Patterns


Structural Patterns
- Adapter Pattern
- Decorator Pattern
- Façade Pattern


Behavioral Patterns
- Command Pattern
- Observer Pattern

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

No Downloads
Views
Total Views
3,951
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
200
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Design Patterns - Part 1 of 2

  1. 1. Design Patterns<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 />Introduction<br />Creational Patterns<br />2.1. Singleton Pattern<br />2.2. Factory Method and Abstract Factory Patterns<br /> Structural Patterns<br />3.1. Adapter Pattern<br />3.2. Decorator Pattern<br />3.3. Façade Pattern<br /> Behavioral Patterns<br />4.1. Command Pattern<br />4.2. Observer Pattern<br />© SAP 2007 / Page 2/104<br />
  3. 3. © SAP 2007 / Page 3<br />Introduction<br />What are Design Patterns?<br />Why do we use them?<br />Types of Design Patterns<br />What Patterns is NOT!<br />
  4. 4. © SAP 2007 / Page 4<br />Introduction to Design Patterns<br />What? <br />Template for writing code<br />Patterns use OO Design Principles<br />Concepts like abstraction, inheritance, polymorphism<br />Why?<br />Readability – familiarity<br />Maintenance<br />Speed – tested, proven development paradigms<br />Communication – shared vocabulary<br />
  5. 5. Types of Design Patterns<br />© SAP 2007 / Page 5<br />
  6. 6. What Patterns are NOT<br />Library of Code?<br />Structure for classes to solve certain problems<br />But aren’t Libraries and Frameworks also Design Patterns?<br />They are specific implementations to which we link our code<br />They use Design Patterns to write their Java Code<br />Is it something to do with s/w architecture?<br />© SAP 2007 / Page 6<br />
  7. 7. Interface == Abstract Class<br />While we study Design Patterns, Abstract Classes and Interface often mean the same thing.<br />© SAP 2007 / Page 7<br />
  8. 8. © SAP 2007 / Page 8<br />Creational Patterns<br />Singleton Pattern<br />Factory Method & Abstract Factory<br />
  9. 9. Singleton Pattern – the simplest pattern<br />Ensures a class has only one instance, and provides a global point of access to it<br />Where to use?<br />Caches<br />Objects that handle registry settings<br />For Logging<br />Device drivers<br />Patterns Component Example of Singleton Pattern Usage:<br />IWDComponentUsagecomponentUsage = patternAccessPoint.getSingleton(IPatternRtApi.TRANSACTION);<br />© SAP 2007 / Page 9<br />
  10. 10. Singleton Class Diagram<br />© SAP 2007 / Page 10<br />
  11. 11. Improving performance<br />© SAP 2007 / Page 11<br />
  12. 12. Create Unique Instance Eagerly<br />Code:<br />public class Singleton {<br /> private static Singleton uniqueInstance = new Singleton();<br /> // other useful instance variables here<br /> private Singleton() {}<br /> public static synchronized Singleton getInstance() {<br /> return uniqueInstance;<br /> }<br /> // other useful methods here<br />}<br />This code is guaranteed to be thread-safe!<br />© SAP 2007 / Page 12<br />
  13. 13. Double-Checked Locking<br />Code:<br />// Danger! This implementation of Singleton not guaranteed to work prior to Java 5<br />public class Singleton {<br /> private volatilestatic Singleton uniqueInstance;<br /> private Singleton() {}<br /> public static Singleton getInstance() {<br />if (uniqueInstance == null) {<br /> synchronized (Singleton.class) {<br /> if (uniqueInstance == null) {<br />uniqueInstance = new Singleton();<br /> }<br /> }<br /> }<br /> return uniqueInstance;<br /> }<br />}<br />This is thread-safe again!<br />© SAP 2007 / Page 13<br />
  14. 14. Factory Method Pattern<br />Creates objects without specifying the exact class to create<br />Most popular OO Pattern<br />© SAP 2007 / Page 14<br />
  15. 15. Compare Two Implementations<br />© SAP 2007 / Page 15<br />
  16. 16. Compare Dependencies<br />© SAP 2007 / Page 16<br />PizzaStore<br />PizzaStore<br />Pizza<br />NYStyle<br />PeppoPizza<br />NYStyle<br />VeggiePizza<br />NYStyle<br />CheesePizza<br />NYStyle<br />PeppoPizza<br />NYStyle<br />VeggiePizza<br />NYStyle<br />CheesePizza<br />ChicagoStyle<br />PeppoPizza<br />ChicagoStyle<br />VeggiePizza<br />ChicagoStyle<br />CheezePizza<br />ChicagoStyle<br />PeppoPizza<br />ChicagoStyle<br />VeggiePizza<br />ChicagoStyle<br />CheezePizza<br />
  17. 17. Explanations<br />© SAP 2007 / Page 17<br />
  18. 18. Class Diagram of Factory Method<br />© SAP 2007 / Page 18<br />
  19. 19. Abstract Factory Pattern<br />Groups object factories that have a common theme<br />Groups together a set of related products<br />Uses Composition and Inheritance<br />Uses Factory Method to create products<br />Essentially FACTORY<br />© SAP 2007 / Page 19<br />
  20. 20. Families – Ingredients / Pizzas<br />© SAP 2007 / Page 20<br />
  21. 21. Factory Method versus Abstract Factory<br />© SAP 2007 / Page 21<br />PizzaStore<br />PizzaStore<br />Pizza<br />Ingredients<br />Pizza<br />Pizza<br />ChicagoStyle<br />CheesePizza<br />PeppoPizza<br />VeggiePizza<br />NYStyle<br />PeppoPizza<br />NYStyle<br />VeggiePizza<br />NYStyle<br />NYStyle<br />CheesePizza<br />ChicagoStyle<br />PeppoPizza<br />ChicagoStyle<br />VeggiePizza<br />ChicagoStyle<br />CheezePizza<br />
  22. 22. Quick Reference: Different Types of Creational Patterns<br />© SAP 2007 / Page 22<br />
  23. 23. © SAP 2007 / Page 23<br />Structural Patterns<br />Adapter Pattern<br />Decorator Pattern<br />Façade Pattern<br />
  24. 24. Adapter Pattern<br />Adapter lets classes work together that couldn't otherwise because of incompatible interfaces<br />© SAP 2007 / Page 24<br />Vendor<br />Class<br />Adapter<br />Your <br />Existing <br />System<br />
  25. 25. Ducks<br />Target Interface<br />public interface Duck {<br /> public void quack();<br /> public void fly();<br />}<br />An implementation the Target Interface<br />public class MallardDuck implements Duck {<br /> public void quack() {<br />System.out.println("Quack");<br /> }<br /> public void fly() {<br />System.out.println("I'm flying");<br /> }<br />}<br />© SAP 2007 / Page 25<br />
  26. 26. Turkeys<br />To-Be-Adapted Interface<br />public interface Turkey {<br /> public void gobble();<br /> public void fly();<br />}<br />An implementation of To-Be-Adapted Interface<br />public class WildTurkey implements Turkey {<br /> public void gobble() {<br />System.out.println("Gobble gobble");<br /> } <br /> public void fly() {<br />System.out.println("I'm flying a short distance");<br /> }<br />}<br />© SAP 2007 / Page 26<br />
  27. 27. Turkey Adapted<br />public class TurkeyAdapter implements Duck {<br /> Turkey turkey; <br /> public TurkeyAdapter(Turkey turkey) {<br />this.turkey = turkey;<br /> } <br /> public void quack() {<br />turkey.gobble();<br /> }<br /> public void fly() {<br /> for(inti=0; i < 5; i++) {<br /> turkey.fly();<br /> }<br /> }<br />}<br />© SAP 2007 / Page 27<br />
  28. 28. Client Application Test Drive<br />public class DuckTestDrive {<br /> public static void main(String[] args) {<br />MallardDuck duck = new MallardDuck(); <br />WildTurkey turkey = new WildTurkey();<br />Duck turkeyAdapter = new TurkeyAdapter(turkey);<br />System.out.println("The Turkey says...");<br />turkey.gobble();<br /> turkey.fly(); <br />System.out.println(" The Duck says...");<br />testDuck(duck); <br />System.out.println(" TheTurkeyAdapter says...");<br />testDuck(turkeyAdapter);<br /> }<br /> static void testDuck(Duck duck) {<br />duck.quack();<br /> duck.fly();<br /> }<br />}<br />© SAP 2007 / Page 28<br />
  29. 29. Adapting Enumerations to Iterators<br />public class EnumerationIterator implements Iterator {<br /> Enumeration enumeration; <br /> public EnumerationIterator(Enumeration enumeration) {<br />this.enumeration = enumeration;<br /> } <br /> public booleanhasNext() {<br /> return enumeration.hasMoreElements();<br /> } <br /> public Object next() {<br /> return enumeration.nextElement();<br /> } <br /> public void remove() {<br /> throw new UnsupportedOperationException();<br /> }<br />}<br />© SAP 2007 / Page 29<br />
  30. 30. Decorator Pattern<br />Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.<br />Decorators have the same super-type as the objects they decorate<br />You can use more than one decorators to wrap an object<br />© SAP 2007 / Page 30<br />Each component can be used on its own, or wrapped by a decorator<br />Concrete Component we can dynamically add new behavior<br />Concrete Decorator has an instance variable for the thing it decorates<br />
  31. 31. java.io uses decorator to extend behaviors<br />© SAP 2007 / Page 31<br />
  32. 32. FilterInputStream.java<br />public class FilterInputStream extends InputStream { <br /> protected volatile InputStream in; <br /> protected FilterInputStream(InputStream in) {<br />this.in = in;<br /> } <br /> public int read() throws IOException {<br />return in.read();<br /> } <br /> public int read(byte b[], int off, intlen) throws IOException {<br />return in.read(b, off, len);<br /> } <br /> public long skip(long n) throws IOException {<br />return in.skip(n);<br /> }<br />}<br />© SAP 2007 / Page 32<br />
  33. 33. Extending java.io  New ClassLowerCaseInputStream.java<br />public class LowerCaseInputStream extends FilterInputStream {<br /> public LowerCaseInputStream(InputStream in) {<br /> super(in);<br /> }<br /> public int read() throws IOException {<br />int c = super.read();<br /> return (c == -1 ? c : Character.toLowerCase((char)c));<br /> } <br /> public int read(byte[] b, int offset, intlen) throws IOException {<br />int result = super.read(b, offset, len);<br /> for (inti = offset; i < offset+result; i++) {<br /> b[i] = (byte)Character.toLowerCase((char)b[i]);<br /> }<br /> return result;<br /> }<br />}<br />© SAP 2007 / Page 33<br />
  34. 34. LowerCaseInputStream.java Test Drive<br />public class InputTest {<br /> public static void main(String[] args) throws IOException {<br />int c;<br /> try {<br />InputStream in = <br /> new LowerCaseInputStream(<br /> new BufferedInputStream(<br /> new FileInputStream("test.txt")));<br /> while((c = in.read()) >= 0) {<br />System.out.print((char)c);<br /> }<br />in.close();<br /> } catch (IOException e) {<br />e.printStackTrace();<br /> }<br /> }<br />}<br />© SAP 2007 / Page 34<br />Set up the FileInputStream and decorate it, first with a BufferedInputStream and then with our brand new LowerCaseInputStream filter<br />
  35. 35. Remember!<br />Inheritance is one form of extension, but there are other ways to do the same<br />Designs should allow behavior to be extended without the need to modify existing code<br />Decorator Pattern involves a set of decorator classes that are used to wrap concrete classes<br />You can wrap a component with any number of decorators<br />We use inheritance to achieve the type matching, but we aren’t using inheritance to get behavior<br />Decorators can result in many small objects in our design, and overuse can be complex<br />© SAP 2007 / Page 35<br />
  36. 36. Decorator and Adapter<br />© SAP 2007 / Page 36<br />
  37. 37. Façade Pattern<br />Facade defines a higher-level interface that makes the sub-system easier to use<br />Do not create design that have a large number of classes coupled together so that changes in one part of the system cascade to other parts<br />When you build a lot of dependencies between many classes, you are building a fragile system that will be costly to maintain and complex for others to understand<br />Patterns Team understands Façade better than many people <br />Threading in Java is also another example of Façade Pattern<br />© SAP 2007 / Page 37<br />
  38. 38. Class Diagram for Façade Pattern<br />© SAP 2007 / Page 38<br />
  39. 39. © SAP 2007 / Page 39<br />Behavioral Patterns<br />Command Pattern<br />Observer Pattern<br />
  40. 40. Command Pattern<br />Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support ‘undo’ operations.<br />A command class is a convenient place to collect code and data related to a command. <br />A command object can hold information about the command, such as its name or which user launched it; and answer questions about it, such as how long it will likely take. <br />The command is a useful abstraction for building generic components<br />The Command Pattern decouples an object, making a request from the one that knows how to perform it<br />“Smart” Command objects implement the request themselves rather than delegating it to a receiver<br />© SAP 2007 / Page 40<br />
  41. 41. Home Automation through Command PatternLight.java<br />public class Light {<br /> public Light() {<br /> }<br /> public void on() {<br />System.out.println("Light is on");<br /> }<br /> public void off() {<br />System.out.println("Light is off");<br /> }<br />}<br />© SAP 2007 / Page 41<br />
  42. 42. Command.java<br />public interface Command {<br />public void execute();<br /> public void undo();<br />}<br />© SAP 2007 / Page 42<br />
  43. 43. LightOnCommand.java<br />public class LightOnCommand implements Command {<br />Light light;<br />public LightOnCommand(Light light) {<br />this.light = light;<br /> }<br /> public void execute() {<br />light.on();<br /> }<br /> public void undo() {<br />light.off();<br /> }<br />}<br />© SAP 2007 / Page 43<br />
  44. 44. LightOffCommand.java<br />public class LightOffCommand implements Command {<br /> Light light;<br /> public LightOffCommand(Light light) {<br />this.light = light;<br /> }<br /> public void execute() {<br />light.off();<br /> }<br /> public void undo() {<br />light.on();<br /> }<br />}<br />© SAP 2007 / Page 44<br />
  45. 45. Test Drive Command Pattern RemoteLoader.java<br />public class RemoteLoader {<br /> public static void main(String[] args) {<br />RemoteControlWithUndoremoteControl = new RemoteControlWithUndo();<br /> Light livingRoomLight = new Light("Living Room");<br />LightOnCommandlivingRoomLightOn = <br /> new LightOnCommand(livingRoomLight);<br />LightOffCommandlivingRoomLightOff = <br /> new LightOffCommand(livingRoomLight);<br />livingRoomLightOn.execute() ;<br />livingRoomLightOff.execute();<br /> }<br />}<br />© SAP 2007 / Page 45<br />
  46. 46. Test Drive Façade and Command Pattern Together<br />You need to look at the code now.<br />© SAP 2007 / Page 46<br />
  47. 47. Class Diagram for Command Pattern<br />© SAP 2007 / Page 47<br />
  48. 48. Observer Pattern<br />Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.<br />© SAP 2007 / Page 48<br />
  49. 49. Subject Interface Isubject.java<br />public interface ISubject {<br /> public void registerObserver( IObserver o ) ;<br /> public void removeObserver( IObserver o ) ;<br /> public void notifyObservers() ;<br />}<br />© SAP 2007 / Page 49<br />
  50. 50. Observer Interface IObserver.java<br />public interface IObserver {<br />public void notify( int temp , int humidity , int pressure ) ;<br />}<br />© SAP 2007 / Page 50<br />
  51. 51. Design Principle<br />© SAP 2007 / Page 51<br />The Subject doesn’t care, it will deliver notifications to any object that implements the Observer Interface<br />Loosely coupled designs allow us to build flexible OO Systems that can handle change because they minimize the interdependency between objects<br />Pull is considered more Correct than Push<br />Swing makes heavy use of the Observer Pattern<br />Observer Pattern defines a one-to-many relationship between objects<br />
  52. 52. © SAP 2007 / Page 52<br />Thank you!<br />
  53. 53. 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 53<br />
  54. 54. © SAP 2007 / Page 54<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 />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×