SlideShare a Scribd company logo
1 of 41
Design Patterns – Part 2 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 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
© SAP 2007 / Page 3 Design Principles OO Design Principles
OO Design Principles Encapsulate what varies (eg: Strategy, State Patterns) Favor composition over inheritance (eg: State, Strategy Patterns) Strive for loosely coupled designs between objects that interact (eg: Observer Pattern) Classes should be open for extension but closed for modification (eg: Factory Method) Depend on abstractions. Do not depend on concrete classes (eg: Factory Method) © SAP 2007 / Page 4
© SAP 2007 / Page 5 Creational Patterns Builder Pattern Lazy Initialization Pattern Object Pool
Builder Pattern Defined Separate the construction of a complex object from its representation so that the same construction process can create different representations. When to use: When you’re building an object in steps, such that each step can be added on to each other to construct the final product Eg: SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "(local)";  builder.InitialCatalog = "Product";  builder.IntegratedSecurity = true;  SqlConnection connection = new SqlConnection(builder.ToString()); © SAP 2007 / Page 6
Class diagram for Builder Pattern © SAP 2007 / Page 7
Lazy Initialization Lazy Initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed It’s a combination of ideas from factory and singleton design patterns: Objects can be created in synchronized method block Use a map to hold objects which have different parameters, if necessary Instantiate the object the first time it is requested for When to Use It is useful when resources are to be conserved © SAP 2007 / Page 8
Code Example – Lazy Initialization Pattern public class Fruit {     private static final Map<String,Fruit>types = new HashMap<String,Fruit>();     private final String type;      private Fruit(String type) { this.type = type;     }      public static synchronized Fruit getFruit(String type) {       Fruit f = types.get(type); // get the instance for that type       if (f == null) { f = new Fruit(type); // lazy initialization types.put(type,f);       }        return f;     } } © SAP 2007 / Page 9
Object Pool – defined Object Pool is a set of initialised objects that are kept ready to use, rather than allocated and destroyed on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object, it returns it to the pool, rather than destroying it.  The object needs to be re-set after the client has finished using the object. The resetting needs to be done by the Pool manager and not the client. If not it leads to cesspools. Inadequate resetting can lead to information leak When to use: When initialization of objects is costly, eg: database connection pools © SAP 2007 / Page 10
© SAP 2007 / Page 11 Structural Patterns Composite Pattern Proxy Pattern
Composite Pattern Composite allows a group of objects to be treated in the same way as a single instance of an object.  The intent of Composite is to compose objects into tree structures to represent part-whole hierarchies. Motivation Differentiating between leaf and branch nodes require complex logic and is error prone Solution: interface which treats complex and primitive objects uniformly When to Use Use when clients need not differentiate between branch and leaf node Eg: Menu structure – one method “display()” should be able to be called on a branch node which in turn delegates it to it’s leaves/branches under it instead of having the client to iterate through the structure © SAP 2007 / Page 12
Composite Pattern Class Diagram © SAP 2007 / Page 13
Component – Leaf – Composite Component is the abstraction for all components, including composite ones  declares the interface for objects in the composition  implements default behavior for the interface common to all classes, as appropriate  declares an interface for accessing and managing its child components  Leaf represents leaf objects in the composition  implements all Component methods  Composite represents a composite Component (component having children)  implements methods to manipulate children  implements all Component methods, generally by delegating them to its children  © SAP 2007 / Page 14
Example Need to look at the source code here © SAP 2007 / Page 15
Proxy Pattern A representative object controls access to another object which may be remote, expensive to create, etc When to use: Remote proxy: Provides a reference to an object located in a different address space on the same or different machine.  Virtual proxy: Allows the creation of a memory intensive object on demand. The object will not be created until it is really needed. Protection (access) proxy: Provides different clients with different levels of access to a target object.  © SAP 2007 / Page 16
Proxy Pattern – ExampleImage.java & Resource hungry RealImage.java interface Image {   public void displayImage(); } class RealImage implements Image {   private String filename;   public RealImage(String filename) {  this.filename = filename; loadImageFromDisk();   }    private void loadImageFromDisk() {     // Potentially expensive operation   }    public void displayImage() { System.out.println("Displaying "+filename); } } © SAP 2007 / Page 17
Proxy Pattern – ExampleProxyImage.java & ProxyExample.java class ProxyImage implements Image {   private String filename;   private Image image;   public ProxyImage(String filename) {  this.filename= filename;   }   public void displayImage() {     if (image == null) {       image = new RealImage(filename);       // load only on demand     } image.displayImage();   } } class ProxyExample {   public static void main(String[] args) { ArrayList<Image> images = new ArrayList<Image>(); images.add( new ProxyImage("HiRes_10MB_Photo1") ); images.add( new ProxyImage("HiRes_10MB_Photo2") ); images.add( new ProxyImage("HiRes_10MB_Photo3") ); images.get(0).displayImage(); // loading necessary images.get(1).displayImage(); // loading necessary images.get(0).displayImage();     // no loading necessary; already done //the third image will never be loaded time saved!   } } © SAP 2007 / Page 18
Proxy Pattern Class Diagram © SAP 2007 / Page 19
Proxy and Decorator PatternsSimilar yet Dissimilar Both have similar class diagrams But they have very different functionality Proxy is used for Representing Subjects Decorator is used to Add Responsibility to the subjects © SAP 2007 / Page 20
© SAP 2007 / Page 21 Behavioral Patterns Strategy Pattern State Pattern Template Method
Strategy Pattern Define a family of algorithms, encapsulate each one, and make them interchangable Algorithms may be selected or changed at runtime When to use: Situations where it is necessary to dynamically swap the algorithms used in an application © SAP 2007 / Page 22
Strategy Pattern ExampleInterface FlyBehavior and it’s implementations public interface FlyBehavior{   public void fly(); } public class 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
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
Strategy Pattern ExampleRubberDuck.java & Simulator public class RubberDuck extends Duck {    public RubberDuck() { flyBehavior = new FlyNoWay(); quackBehavior = new Squeak();   }   public void display() { System.out.println("I'm a rubber duckie");   } } public class MiniDuckSimulator1 {    public static void main(String[] args) {     Duck model = new RubberDuck(); model.performFly(); model.setFlyBehavior(new FlyRocketPowered()); model.performFly();   } } © SAP 2007 / Page 25
Strategy Pattern Class Diagram © SAP 2007 / Page 26
State Pattern Allow an object to alter its behavior when its internal state changes. When to use: Situations where the object behavior changes depending on the state it is at Similar to Strategy Pattern: Intent is different – State Pattern is built around discrete states, and the context objects change state over time according to some well defined state transitions Changing behavior is built into the scheme for State Pattern Strategy Pattern does not encourage its objects to have well-defined set of transitions between states © SAP 2007 / Page 27
State Pattern ExampleState.java public interface State {    public void insertQuarter();   public void ejectQuarter();   public void turnCrank();   public void dispense(); } © SAP 2007 / Page 28
State PatternGumballMachine.java public class GumballMachine { State soldOutState;   State noQuarterState;   State hasQuarterState;   State soldState;   State state = soldOutState; int count = 0;   public GumballMachine(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
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
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
State Pattern Class Diagram © SAP 2007 / Page 32
© SAP 2007 / Page 33 Conclusion Final Recap When to Use
Quick Reference: Different Types of Creational Patterns © SAP 2007 / Page 34
Quick Reference: Different Types of Structural Patterns © SAP 2007 / Page 35
Quick Reference: Different Types of Behavioral Patterns © SAP 2007 / Page 36
Quick Reference: When to Use – Creational Patterns © SAP 2007 / Page 37
Quick Reference:  When to Use – Structural Patterns © SAP 2007 / Page 38
Quick Reference:  When to Use – Behavioral Patterns © SAP 2007 / Page 39
© SAP 2007 / Page 40 Thank you!
References Head First Design Patterns Eric & Elizabeth Freeman with Kathy Sierra & Bert Bates Wikipedia http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 YouTube http://www.youtube.com/codingkriggs © SAP 2007 / Page 41

More Related Content

What's hot

P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
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 Manykenatmxm
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Herman Peeren
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael Heron
 
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & CompositeSarath C
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objectsPrem Kumar Badri
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns IllustratedHerman Peeren
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
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 APIsSubhransu Behera
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesHoang Nguyen
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design PatternGanesh Kolhe
 
Desing Patterns Summary - by Jim Fawcett
Desing Patterns Summary - by Jim FawcettDesing Patterns Summary - by Jim Fawcett
Desing Patterns Summary - by Jim FawcettDareen Alhiyari
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template PatternJonathan Simon
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.pptKarthik Sekar
 
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 Patterneprafulla
 

What's hot (20)

P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
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
 
Design patterns illustrated-2015-03
Design patterns illustrated-2015-03Design patterns illustrated-2015-03
Design patterns illustrated-2015-03
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & Composite
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
SOLID
SOLIDSOLID
SOLID
 
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
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design Pattern
 
Desing Patterns Summary - by Jim Fawcett
Desing Patterns Summary - by Jim FawcettDesing Patterns Summary - by Jim Fawcett
Desing Patterns Summary - by Jim Fawcett
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 
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
 

Similar to Design Patterns - Part 2 of 2

Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design PatternsDang Tuan
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
Gang of four Proxy Design Pattern
 Gang of four Proxy Design Pattern Gang of four Proxy Design Pattern
Gang of four Proxy Design PatternMainak Goswami
 
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 PatternNishith Shukla
 
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 PatternsLalit Kale
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 

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

Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Sling Models Overview
Sling Models OverviewSling Models Overview
Sling Models Overview
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Gang of four Proxy Design Pattern
 Gang of four Proxy Design Pattern Gang of four Proxy Design Pattern
Gang of four Proxy Design Pattern
 
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
 
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
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Design Patterns and Usage
Design Patterns and UsageDesign Patterns and Usage
Design Patterns and Usage
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Recently uploaded

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

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
  • 7. Class diagram for Builder Pattern © SAP 2007 / Page 7
  • 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
  • 13. Composite Pattern Class Diagram © SAP 2007 / Page 13
  • 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
  • 15. Example Need to look at the source code here © SAP 2007 / Page 15
  • 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
  • 19. Proxy Pattern Class Diagram © SAP 2007 / Page 19
  • 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
  • 26. Strategy Pattern Class Diagram © SAP 2007 / Page 26
  • 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
  • 32. State Pattern Class Diagram © SAP 2007 / Page 32
  • 33. © SAP 2007 / Page 33 Conclusion Final Recap When to Use
  • 34. Quick Reference: Different Types of Creational Patterns © SAP 2007 / Page 34
  • 35. Quick Reference: Different Types of Structural Patterns © SAP 2007 / Page 35
  • 36. Quick Reference: Different Types of Behavioral Patterns © SAP 2007 / Page 36
  • 37. Quick Reference: When to Use – Creational Patterns © SAP 2007 / Page 37
  • 38. Quick Reference: When to Use – Structural Patterns © SAP 2007 / Page 38
  • 39. Quick Reference: When to Use – Behavioral Patterns © SAP 2007 / Page 39
  • 40. © SAP 2007 / Page 40 Thank you!
  • 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%