Creational Design Patterns

Slides:



Advertisements
Similar presentations
Design Patterns.
Advertisements

Creational Design Patterns. Creational DP: Abstracts the instantiation process Helps make a system independent of how objects are created, composed, represented.
Creational Patterns, Abstract Factory, Builder Billy Bennett June 11, 2009.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Design Pattern Course Builder Pattern 1 Mahdieh Monzavi AmirKabir University of Technology, Department of Computer Engineering & Information Technology.
1 Creational Patterns CS : Software Design Winter /T8.
Builder A Creational Design Pattern A Presentation by Alex Bluhm And.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
1 1.Introduction 2.Factory Method 3.Abstract Factory 4.Prototype 5.Builder 6.Singleton.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Design Patterns.
Abstract Factory Design Pattern making abstract things.
Software Components Creational Patterns.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method Pattern.
The Factory Method Design Pattern Motivation: Class / Type separation – Abstract class serves as type definition and concrete class provides implementation.
CDP-1 9. Creational Pattern. CDP-2 Creational Patterns Abstracts instantiation process Makes system independent of how its objects are –created –composed.
Шаблоны проектирования ООП. Принципы ООП Инкапсуляция Наследование Полиморфизм Абстракция данных.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Define an interface for creating an object, but let subclasses decide which class to instantiate.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
SWE 316: Software Design and Architecture – Dr. Khalid Aljasser Objectives Lecture 13 Creational Design Pattern SWE 316: Software Design and Architecture.
CS 590L – Distributed Component Architecture 02/20/2003Uttara Paingankar1 Design Patterns: Factory Method The factory method defines an interface for creating.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Creational Design Patterns Yaodong Bi December 21, 2015December 21, 2015December 21, 2015.
Design Patterns Introduction
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Reference – Object Oriented Software Development Using Java - Jia COP 3331 Object Oriented Analysis and Design Chapter 10 – Patterns Jean Muhammad.
Chapter 7 Creational Design Pattern. Process Phases Discussed in This Chapter Requirements Analysis Design Implementation ArchitectureFrameworkDetailed.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Overview of Creational Patterns ©SoftMoore ConsultingSlide 1.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
Abstract Factory pattern Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Design Pattern : Builder SPARCS 04 고윤정. Main Concepts One of Creational Patterns. Process to construct Complex object in Abstract type. –Use the same.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Abstract Factory Pattern
Factory Method Pattern
Design Pattern Catalogues
Design Patterns C++ Java C#.
Factory Patterns 1.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Design Patterns C++ Java C#.
Software Design and Architecture
Design Patterns with C# (and Food!)
Factory Method Pattern
Abstract Factory Pattern
Intent (Thanks to Jim Fawcett for the slides)
Design Patterns - A few examples
Software Engineering Lecture 7 - Design Patterns
SE-2811 Software Component Design
CSE 432 Presentation GoF: Factory Method PH: “To Kill a Singleton”
Prototype Pattern 1.
Singleton design pattern
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
Lesson 5: More on Creational Patterns
Design pattern Lecture 6.
Creational Patterns.
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
5. Strategy, Singleton Patterns
Presentation transcript:

Creational Design Patterns Yaodong Bi September 22, 2005

Creational design patterns Factory Abstract Factory Prototype Singleton Builder

Factory Problem Design Purpose Design Pattern Summary The client needs to create an object of a subclass, but it does not know the subclass until runtime. Design Purpose Create individual objects in situations where the constructor alone is inadequate. Design Pattern Summary Use methods to return required objects

Factory – an example Client stack MyStack void useStack(Stack s) { while (condition) { stackn = new Stack(); //????? } Stack = new MyStack(); useStack(s); //????? stack +push() +pop() MyStack +push() +pop()

Factory - structure Client Product Creator Concrete Creator Concrete void useProduct(Creator c) { Product p = c.factoryMethod(); // use p } …. Creator c = new ConcreteCreator(); useProduct(c); Client +useProduct() Product Creator +factoryMethod() Product factorMethod() { Return new ConcreteProduct(); } Concrete Creator +factoryMethod() Concrete Product

Factory - participants Product defines the interface of objects the factory method creates. ConcreteProduct implements the Product interface. Creator declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. Creator and Product could be the same class ConcreteCreator overrides the factory method to return an instance of a ConcreteProduct. Client It depends only on Product and Creator. Collaborations Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.

Factory – sequence diagram Concrete Creator Client Creator Product Concrete Product factoryMethod() factoryMethod() constructor() op() op()

Factory – sample code

Factory – comments Factory methods are necessary for the OCP on object creation Factory methods make the DIP more viable Factory Method gives subclasses a hook for providing an extended version of an object Creator could be a concrete class providing a default implementation of Product Creator and Product could be the same class There is an advantage of using a separate creator class for the product The product and its creation are separate concerns When the product is very complex, the creator can create products (even the first one) as demanded – lazy loading

Abstract Factory Design purpose Pattern summary Provide an interface for creating families of related or dependent objects without specifying their concrete classes Pattern summary Capture family creation in a class containing a factory method for each class in the family

Abstract Factory – examples Word processor for different window systems Word processor is designed to a set of interfaces of graphical elements Each windows system manufactures its own set of button, windows, dialogs, etc Each installation of the word processor is given a windows system (concrete factory) Kitchen showroom The program is designed to a common set of cabinets, counters, etc Each different style of kitchen furniture provide the furniture in the style (classic, contemporary, etc) Each individual kitchen showroom is given a style (concrete factory) GUI themes

Abstract Factory - structure ProductA ProductA1 ProductA2 Factory +createProductA() +createproductB() Client Factory1 +createProductA() +createproductB() Factory2 +createProductA() +createproductB() ProductB ProductB1 ProductB2 ProductB createProductB { Return new ProductB1(); } ProductA createProductA { Return new ProductA1(); }

Abstract Factory - participants ProductA and ProductB defines the interface of a family of objects. ProductA1, ProductB1, ProductA2, and ProductB2 Two separate families of product implementation. Factory Defines the interface of the factory that returns the products Factory1 and Factory2 Concrete factories that can produce products of the family. Factory1 produces ProductA1 and ProductB1, Factory2 produces ProductA2 and ProductB2 Client It depends only on the interfaces of the family products and the factory interface. Collaborations The client asks a subclass of Factory to create concrete products of ProductA and productB.

Abstract Factory – sample code

Abstract Factory – comments Use the Abstract Factory when a client needs to use one of multiple families of products It is hard to add new types of products since adding a new product means adding a new factory method to the AbstractFactory interface and its all subclasses When families of products are different combinations of the same set of products and/or the # of families is large, many ConcreteFactory subclasses would be needed. In this case, the Prototype pattern may be employed

Prototype Design purpose Pattern summary Create a set of almost identical objects whose type is determined at runtime Pattern summary Assume that a prototype instance is known; clone it whenever a new instance is needed

Prototype – examples Kitchen showroom A showroom may have all cabinets in one style, counters in one style, etc Instead of creating a factory for each possible combination of different furniture in different styles, each individual showroom is given a prototype of each type of furniture of a style Each prototype can clone itself

Prototype - structure Prototype Client ConcreteProduct1 +clone() +otherOperations() prototype Client +anOperation() ConcreteProduct1 +clone(); +otherOperations(); ConcreteProduct2 +cone(); +otherOperations(); Prototype p = prototype.clone(); Return a copy of itself Return a copy of itself

Prototype - participants defines the interface (an operation) of cloning itself. ConcreteProduct1 and ConcreteProduct2 Concrete objects that can clone themselves. Client Obtain more objects by asking them to clone themselves. Collaborations The client asks the prototype to clone itself for a new object of the prototype.

Shallow vs. deep cloning (coping) prototype ref Client +anOperation() :Prototype +clone() -Nested:ref :Nested +op() -data prototype ref Client +anOperation() :Prototype +clone() -Nested:ref :Nested +op() -data ref clone:Prototype +clone() -Nested:ref Shallow cloning prototype ref Client +anOperation() :Prototype +clone() -Nested:ref :Nested +op() -data ref clone:Prototype +clone() -Nested:ref clone:Nested +op() -data Deep cloning

Shallow vs. deep cloning //Shallow cloning: sample code Class Prototype implements Cloneable { private int x; private Nested ref = new Nested(); public Prototype clone() { Prototype p = new Prototype() p.x = this.x; p.ref = this.ref; return p; } Class Nested { int data; public void op() {} Class Client { private Prototype prototype = new Prototype(); public void op() { Prototype clone = prototype.clone(); // use clone //Deep cloning: sample code Class Prototype implements Cloneable { private int x; private Nested ref = new Nested(); public Prototype clone() { Prototype p = new Prototype() p.x = this.x; p.ref = this.ref.clone(); return p; } Class Nested implements Cloneable { int data; public void op() {} public Nested clone() { Nested n = new Nested() n.data = this.data; return n; Class Client { // the same Client as for Shallow cloning

Prototype – sample code

Prototype – comments If the clone does not need to be identical as its original, a factory method may be used Be aware of the shallow cloning problem – to the deepest level When prototypes can be grouped in a small # of different combinations, the Abstract Factory may be suitable

Singleton Design purpose Pattern summary Ensure there is exactly one instance of a class Be able to obtain the instance from anywhere in the application Pattern summary Make the constructor of class private or protected, define a private static attribute of the class, define a public accessor to it.

Singleton – an example A concrete factory in the Abstract Factory pattern in most cases should have only one instance – all objects are produced by the same factory In JGrasp (or any IDE), we want one JVM (Singleton) for all Java programs.

Singleton - structure Singleton soleInstance +static getInstance(); +operations() -data soleInstance <<static>> return soleInstance;

Singleton - participants Declare all constructors private and provide only one entry for obtaining a reference to the sole instance. Client Clients can get to the sole instance of Singleton by asking Singleton to return a reference to it. Collaborations A client can only call getInstance() to get a reference to the sole instance. A client cannot create any instance of Singleton

Singleton – sample code class Singleton { // since private no client can access // this reference directly private static Singleton soleInstance = new Singleton(); private int data; // since protected, no client can // create any instance directly protected Singleton(); // the only entry for clients to get a // reference to the sole instane public static Singleton getInstance() { return soleInstance; } // other operations public void operations() { } class Client1 { void anOperation() { // Singleton ref = new Singleton(); // illegal since Singleton() is protected Singleton ref = Singleton.getInstance(); ref.operations(); } class Client2 { // use ref NOTE: objects of Client1 and Client2 would all share the same sole instance of Singleton.

Singleton – comments Lazy loading Not thread safe (Java) If the object of Singleton is complex, it may take much resource to create. We better create the object only when it is referenced – lazy loading Change the body of getInstance() with the following if (soleInstance == null) { soleInstance = new Singleton(); } return soleInstance; Not thread safe (Java) Two concurrent threads could cause two instances created if executed concurrently Solution: Make getInstance() synchronized All static members? Since there is only one instance, why don’t we just make all members static? If yes, then the instance may not fit with the rest of the application: e.g., display(Employee) would not work if singleton CEO is all static

Builder Design purpose Pattern summary Separate the construction of a complex object from its representation so that the same construction process can create different representations Pattern summary Use a builder to encapsulate the representation.

Builder – an example Language translator Translate a Java programs to other programming languages (C++, Delphi) The translation process is the same for all target languages – mapping “import” to something (“include” in C++) Each target language has a builder to handle each keyword/structure

Builder - structure Builder builder Client Director BuilderA BuilderB +buildPartA() +buildPartB() +buildPartC() director builder Client +madeProduct() Director +buildProduct() BuilderA +buildPartA() +buildPartB() +buildPartC() +getProductA() BuilderB +buildPartA() +buildPartB() +buildPartC() +getProductB() For (every part needed in product) if (part A) builder.buildPartA(); else if (part B) builder.buildPartB(); else if (part C) builder.buildPartC(); } ProductA ProductB

Builder - participants ProductA and ProductB Concrete products that are created by different builders. Director A class that knows what steps it takes to build a product, but it does not know how each step is to be carried out or does not know how each part may be added to the final product Builder Defines an interface for concrete builders BuildlerA and BuilderB Concrete builders who know to construct each part of the product and add it to the final product Client A client selects a director and a concrete builder to build the product it needs. The client asks the concrete builder to return the final constructed product Collaborations The director knows what parts are needed for the final product and the selected concrete builder knows how to product the part and add it to the final product.

Builder – sequence diagram Client Director Concrete Builder Product builder = constructor() constructor() constructor(builder) buildProduct() buildPartA() addPartA() buildPartB() addPartB() buildPartC() addPartC() getProduct()

Builder – sample code Class Director { Class Product { private Builder b; Director(Builder b) {this.b = b;} void buildProduct() { for each part in Product { if (partA) b.buildPartA(); else if (partB) b.buildPartB(); else if (partC) b.buildPartC(); } client() { Builder b = new ConcreteBuilder(); Director d = new Director(b); d.buildProduct() FinalProduct fp = b.getResult(); Class Product { addPartA() {} addPartB() {} addPartC() {} … } Class ConcreteBuilder implements Builder { Private: Product p; ConcreteBuilder() { p = new Product(); buildPartA() {… p.addParta(); … } buildPartB() {… p.addPartb(); … } buildPartC() {… p.addPartc(); … } Product getResult() { return p; }

Creational design patterns Factory Abstract Factory Prototype Singleton Builder