1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.

Slides:



Advertisements
Similar presentations
Chapter 5: The Singleton Pattern
Advertisements

Lecture 5: Interfaces.
CSC 243 – Java Programming, Spring 2013 March 26, 2013 Week 8, java.lang.Clonable & java.io.Serializable Interfaces.
Plab – Tirgul 12 Design Patterns
Jan Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Oct Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
IEG3080 Tutorial 7 Prepared by Ryan.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Spring 2010ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
1 Scenario: Audio Clip Imagine that your application played an audio clip Based on user action, a different audio clip may begin playing You want only.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Winter 2007ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
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.
Singleton and Basic UML CS340100, NTHU Yoshi. What is UML Unified Modeling Language A standardized general-purpose modeling language in the field of software.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
CDP-1 9. Creational Pattern. CDP-2 Creational Patterns Abstracts instantiation process Makes system independent of how its objects are –created –composed.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Design Patterns Introduction
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
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.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
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.
PROTOTYPE. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Polymorphism and access control. RHS – SOC 2 What is polymorphism? In general: the ability of some concept to take on different forms In Java: the ability.
Web Design & Development Lecture 9
Design Patterns: Brief Examples
MPCS – Advanced java Programming
Inheritance and Polymorphism
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Creational Design Patterns
CSE 331 Cloning objects slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Chapter 14 Abstract Classes and Interfaces
Interfaces.
5. Strategy, Singleton Patterns
Presentation transcript:

1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design

2 Outline  Three More Design Patterns  Singleton (creational)  Factory (creational)  Flyweight (structural)

3 To use new or to not use new? That is the question.  Since most object-oriented languages provide object instantiation with new and initialization with constructors  There may be a tendency to simply use these facilities directly without forethought to future consequences  The overuse of this functionality often introduces inflexibility in the system

4 Creational Patterns  Creational patterns describe object-creation mechanisms that enable greater levels of reuse in evolving systems: Builder, Singleton, Prototype  The most widely used is Factory  This pattern calls for the use of a specialized object solely to create other objects

5 Recurring Problem Some classes have only one instance. For example, there may be many printers in a system, but there should be only one printer spooler How do we ensure that a class has only one instance and that instance is easily accessible? Solution Have constructor return the same instance when called multiple times Takes responsibility of managing that instance away from the programmer It is simply not possible to construct more instances OO Design Pattern Singleton

6 UML General form as UML (From

7 Java Code General Form // NOTE: This is not thread safe! public class Singleton { private static Singleton uniqueInstance; // other useful instance variables here private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } // other useful methods here }

8 Example Used in a final project names changed to protect identity /** This class is a DECORATOR of ArrayList. Its purpose is to make * sure there are no duplicate names anywhere in the universe. * That's why it's SINGLETON; because many classes use it but * there should be only one. */ public class NamesList implements Serializable { private ArrayList npcNames; private static NamesList self; private NamesList() { npcNames = new ArrayList (); } public static syncronized NamesList getInstance() { if (self == null) { self = new NamesList(); } return self; }

9 OO Design Pattern Factory Method  Name: Factory Method  Problem: A Client needs an object and it doesn't know which of several objects to instantiate  Solution: Let an object instantiate the correct object from several choices. The return type is an abstract class or an interface type.

10 Characteristics  A method returns an object  The return type is an abstract class or interface  The interface is implemented by two or more classes or the class is extended by two or more classes

11 Example from Java  Border is an interface Border  AbstractBorder is an abstract class that implements Border AbstractBorder  BorderFactory has a series of static methods returning different types that implement Border BorderFactory  This hides the implementation details of the subclasses  Factory methods such as createMatteBorder createEthedBorder createTitleBorder directly call constructors of the subclasses of AbstractBorder return priority + ":" + myText;

12 One type JFrame f = new JFrame(); f.setSize(250, 100); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel toBeBordered = new JPanel(); Border border = BorderFactory.createMatteBorder(2,1,5,9,Color.RED); toBeBordered.add(new JLabel("" + border.getClass())); toBeBordered.setBorder(border); f.getContentPane().add(toBeBordered); f.setVisible(true);

13 Another type JFrame f = new JFrame(); f.setSize(250, 100); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel toBeBordered = new JPanel(); Border border = BorderFactory.createEtchedBorder(); toBeBordered.add(new JLabel("" + border.getClass())); toBeBordered.setBorder(border); f.getContentPane().add(toBeBordered); f.setVisible(true);

14 Two others Border border = BorderFactory.createTitledBorder("Title"); Border border = BorderFactory.createLineBorder(Color.GREEN, 12);

15 Lots of Subclasses javax.swing.border.AbstractBorder java.lang.Object javax.swing.border.AbstractBorder All Implemented Interfaces: SerializableSerializable, BorderBorder Direct Known Subclasses: BasicBorders.ButtonBorderBasicBorders.ButtonBorder, BasicBorders.FieldBorder, BasicBorders.MarginBorder, BasicBorders.MenuBarBorder, BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, LineBorder, MetalBorders.ButtonBorder, MetalBorders.Flush3DBorder, MetalBorders.InternalFrameBorder, MetalBorders.MenuBarBorder, MetalBorders.MenuItemBorder, MetalBorders.OptionDialogBorder, MetalBorders.PaletteBorder, MetalBorders.PopupMenuBorder, MetalBorders.ScrollPaneBorder, MetalBorders.TableHeaderBorder, MetalBorders.ToolBarBorder, TitledBorderBasicBorders.FieldBorder BasicBorders.MarginBorderBasicBorders.MenuBarBorder BevelBorderCompoundBorderEmptyBorderEtchedBorder LineBorderMetalBorders.ButtonBorder MetalBorders.Flush3DBorderMetalBorders.InternalFrameBorder MetalBorders.MenuBarBorderMetalBorders.MenuItemBorder MetalBorders.OptionDialogBorderMetalBorders.PaletteBorder MetalBorders.PopupMenuBorderMetalBorders.ScrollPaneBorder MetalBorders.TableHeaderBorderMetalBorders.ToolBarBorder TitledBorder

16 NumberFormat, a factory  Objects can be returned without directly using new double amount = ; NumberFormat formatter = NumberFormat.getCurrencyInstance(); System.out.println(formatter.format(amount)); Output if the computer is set to US Locale $12, Change the computer setting to Germany Locale and we get this: ,12 €

17 What Happened?  getCurrencyInstance returns an instance of DecimalFormat where methods like setCurrency help build the appropriate object  It encapsulates the creation of objects  Can be useful if the creation process is complex, for example if it depends on settings in configuration files or the jre or the OS

18 Behind the scenes  Client: main method  Factory Method: getCurrencyInstance  Product: a properly configured instance of DecimalFormat  This is another example of Factory in use

19 Design Pattern Flyweight Recurring Problem Each product in family in Factory patterns is a subclass. How to avoid implementing so many subclasses? Solution Use a master instance object as a prototype to construct other instances (clone) instead of using new.

20 UML for the Prototype Pattern (From )

21 Participants: It is all about cloning Prototype Defines interfaces of objects to be created Defines a clone( ) method ConcretePrototype Implements the Prototype interface Implements clone( ) Client Creates new instances by cloning the prototype

22 Cloning in Java Classes that are associated with instances that can be cloned must implement the java.lang.Cloneable interface This is a marker interface: there are no methods in Cloneable It is a contract that states that all fields are cloneable. This will be checked by the compiler Object clone() is a method of Object If the object is not cloneable, jvm throws a new CloneNotSupportedException()

23 Use Example: Text Messages public class TextMsg implements Cloneable { private String myText; private int priority; public TextMsg(String textIn, int priorityIn) { myText = textIn; priority = priorityIn; } public void setText(String textIn) { myText = textIn; } public String toString() { return priority + ":" + myText; } public TextMsg clone(int newPriority) { return new TextMsg(myText, newPriority); }

24 Use Example: Text Messages public class TextMessageRunner { public static void main(String[] args) { TextMsg toBoss = new TextMsg("Hello Sir", 1); TextMsg toWife = toBoss; TextMsg toFriend = toBoss.clone(2); toWife.setText("Bye Honey"); toFriend.setText("Hey, Pal"); System.out.println(toBoss); // 1:Bye, Honey System.out.println(toWife); // 1:Bye, Honey System.out.println(toFriend); // 2:Hey, Pal }

25 Shallow versus Deep Copies Object a = Object b Makes a shallow copy (copies the reference to b into a) Changes to a or b will effect a and b. Object clone() Makes a deep copy (byte-for-byte) Primitives within cloned object are copied by value Objects within cloned object are copied by reference Can define own clone( ) method with a different semantics, as done in TextMsg example. If you don’t do this, you will have to cast from Object

26 Summary Used when classes only differ in properties, not behavior The cloned object copies the state of the original object