Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.

Slides:



Advertisements
Similar presentations
Creational Design Patterns. Creational DP: Abstracts the instantiation process Helps make a system independent of how objects are created, composed, represented.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Jan Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Oct Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
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.
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.
7/16/2015Singleton creational design pattern1 Eivind J. Nordby Karlstad University Dept. of Computer Science.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
OOP Languages: Java vs C++
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Computing IV Singleton Pattern Xinwen Fu.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
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.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
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.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Singleton Duchenchuk Volodymyr Oksana Protsyk. 2 /48.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
CSI 3125, Preliminaries, page 1 Compiling the Program.
Virtual FunctionstMyn1 Virtual Functions A virtual function is declared in a base class by using the keyword virtual. A function that you declare as virtual.
Design Patterns Introduction
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Web Design & Development Lecture 9
Design Patterns: Brief Examples
Design Patterns C++ Java C#.
Design Patterns C++ Java C#.
More Design Patterns 1.
PH page GoF Singleton p Emanuel Ekstrom.
More Design Patterns 1.
Introduction to Classes
Object Oriented Programming
Singleton Pattern Pattern Name: Singleton Pattern Context
Singleton design pattern
CS 350 – Software Design Singleton – Chapter 21
Classes and Objects CGS3416 Spring 2019.
CSG2H3 Object Oriented Programming
Chapter 5 Classes.
Presentation transcript:

Singleton Pattern

Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization versus usage ordering Solution Provide a global access method (static in C++) First use of the access method instantiates the class Constructors for instance are made private

Structure

Singleton Model

Code C++ Java

Here's a declaration of such a class: class Singleton { public: static Singleton* Instance(); protected: Singleton(); Singleton(const Singleton&); Singleton& operator= (const Singleton&); private: static Singleton* pinstance; };

The class's implementation looks like this: Singleton* Singleton::pinstance = 0; // initialize pointer Singleton* Singleton::Instance () { if (pinstance == 0) // is it the first call? { pinstance = new Singleton; // create sole instance } return pinstance; // address of sole instance } Singleton::Singleton() { //... perform necessary instance initializations }

The class's implementation looks like this: Note that this design is bullet-proof—all the following Instance() calls return a pointer to the same instance: Singleton *p1 = Singleton::Instance(); Singleton *p2 = p1->Instance(); Singleton & ref = * Singleton::Instance();

Singleton Class Template template class Singleton { public: // Global access point static TYPE *instance(); private: // Default constructor. Singleton(); // Contained instance. TYPE s_instance; }; Good example of when to use C++ templates When you would have “cut and paste” classes Parameterized by a concrete type That we want to make a singleton instance Allows many singletons to be declared & defined Using a single template Notice constructor and variable are private

Singleton Template Definition // Initialize the static // instance pointer template TYPE *Singleton::s_instance = 0; // Global access point template TYPE * Singleton::instance (void) { // check for existing instance if (Singleton ::s_instance == 0) { // may want a try/catch here Singleton ::s_instance = new Singleton ; } return Singleton ::s_instance; }; Initialization of static s_instance variable Outside class declaration Outside method definition Done before any method in compilation unit is called Instance accessor method can then check For a 0 instance pointer And create a new instance if so Same object is always returned by accessor

Using the Singleton Template Foo *f1 = Singleton ::instance(); Foo *f2 = Singleton ::instance(); Need a single instance E.g., a common buffer of text tokens from a file Shared across multiple points in the code Need to share buffer Copying is wasteful Need to refer to same object instance What about deleting these instances?

JAVA Singleton Defines an Instance operation (class operation) that lets clients access its unique instance May be responsible for creating its own unique instance public class Singleton { private static Singleton instance = null; public static Singleton getSingleton() { if( instance == null ) { instance = new Singleton(); } return instance; }

Collaborations Clients access a Singleton instance solely through Singleton's interface public class Client { public static void main(String[] args) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); if (s1 == s2 ) { System.out.println( “ Single object ” ); } }

Consequences Controlled access to sole instance Reduced name space Avoids global variables Permits refinement of operations & representation Subclassing allows selection at run-time Permits variable number of instances Change operation that grants access to the Singleton instance More flexible than class operations Static functions in C++ - cannot be virtual

Implementation Ensuring a unique instance Can hide operation that creates the instance behind a class operation Can guarantee that creation & initialization occur correctly Since _instance is a pointer to a Singleton object - change can be made at run-time to a different Singleton object (subtyping) Allows instantiation of object at time client specifies Static initialization time is not under control of client

Subclassing the Singleton class Question: which subclass instance Put decision in Singleton's Instance operation Put implementation of Instance in subclass  programmer needs to select correct subclass Registry of singletons Singleton classes - register their singleton instance in a known location Registry - maps between string names & singletons When singleton is needed - registry is searched  common interface required for all Singleton classes registration - cannot occur in constructor – circular Workaround static implementation of each subclass & have constructor register subclass singleton