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

More Related Content

What's hot

P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03
Herman Peeren
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
Michael Heron
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
kenatmxm
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & Composite
Sarath C
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
Herman Peeren
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
Prem Kumar Badri
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
Onkar Deshpande
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
Naga Muruga
 
SOLID
SOLIDSOLID
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Pattern
eprafulla
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
Shakil Ahmed
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
Anjan Kumar Bollam
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
Subhransu Behera
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
Karthik Sekar
 

What's hot (20)

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & Composite
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
SOLID
SOLIDSOLID
SOLID
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 

Viewers also liked

SITIST 2016 Dev - Design Patterns in ABAP Objects
SITIST 2016 Dev - Design Patterns in ABAP ObjectsSITIST 2016 Dev - Design Patterns in ABAP Objects
SITIST 2016 Dev - Design Patterns in ABAP Objects
sitist
 
Design patterns in_object-oriented_abap_-_igor_barbaric
Design patterns in_object-oriented_abap_-_igor_barbaricDesign patterns in_object-oriented_abap_-_igor_barbaric
Design patterns in_object-oriented_abap_-_igor_barbaric
Knyazev Vasil
 
LSA++ english version
LSA++ english versionLSA++ english version
LSA++ english version
Mauricio Cubillos Ocampo
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution ReportFridz Felisco
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
Rothana Choun
 
Command pattern
Command patternCommand pattern
Command pattern
Shakil Ahmed
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
Shakil Ahmed
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
melbournepatterns
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
Jonathan Simon
 
Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603melbournepatterns
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
Shahriar Iqbal Chowdhury
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorialPiyush Mittal
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - AdapterManoj Kumar
 
SAP S/4HANA - What it really is and what not
SAP S/4HANA - What it really is and what notSAP S/4HANA - What it really is and what not
SAP S/4HANA - What it really is and what not
tamas_szirtes
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
guy_davis
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
Shahriar Hyder
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
Adeel Riaz
 
Implementing the Adapter Design Pattern
Implementing the Adapter Design PatternImplementing the Adapter Design Pattern
Implementing the Adapter Design Pattern
ProdigyView
 

Viewers also liked (20)

SITIST 2016 Dev - Design Patterns in ABAP Objects
SITIST 2016 Dev - Design Patterns in ABAP ObjectsSITIST 2016 Dev - Design Patterns in ABAP Objects
SITIST 2016 Dev - Design Patterns in ABAP Objects
 
Design patterns in_object-oriented_abap_-_igor_barbaric
Design patterns in_object-oriented_abap_-_igor_barbaricDesign patterns in_object-oriented_abap_-_igor_barbaric
Design patterns in_object-oriented_abap_-_igor_barbaric
 
LSA++ english version
LSA++ english versionLSA++ english version
LSA++ english version
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution Report
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Command pattern
Command patternCommand pattern
Command pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
 
Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorial
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
 
SAP S/4HANA - What it really is and what not
SAP S/4HANA - What it really is and what notSAP S/4HANA - What it really is and what not
SAP S/4HANA - What it really is and what not
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Implementing the Adapter Design Pattern
Implementing the Adapter Design PatternImplementing the Adapter Design Pattern
Implementing the Adapter Design Pattern
 

Similar to Design Patterns - Part 1 of 2

Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
SWIFTotter Solutions
 
Design patterns
Design patternsDesign patterns
Design patterns
Anas Alpure
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
Ólafur Andri Ragnarsson
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Steven Smith
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
kristinatemen
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
Oliver Gierke
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
Ólafur Andri Ragnarsson
 
Implementing DDD with C#
Implementing DDD with C#Implementing DDD with C#
Implementing DDD with C#
Pascal Laurin
 
Spring boot
Spring bootSpring boot
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
Lalit Kale
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
ssuser7f90ae
 
Design Patterns
Design PatternsDesign Patterns
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Raffi Khatchadourian
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1Dhaval Dalal
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
AdilAijaz3
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 

Similar to Design Patterns - Part 1 of 2 (20)

Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Design patterns
Design patternsDesign patterns
Design patterns
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
Implementing DDD with C#
Implementing DDD with C#Implementing DDD with C#
Implementing DDD with C#
 
Spring boot
Spring bootSpring boot
Spring boot
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 

Recently uploaded

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
gb193092
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 

Recently uploaded (20)

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 

Design Patterns - Part 1 of 2

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