Singleton Duchenchuk Volodymyr Oksana Protsyk. 2 /48.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Chapter 5: The Singleton Pattern
Advanced C++ Programming Anton Kaiser, Summer Term 2012.
SE2811 Week 7, Class 2 The Gang of Four and more … Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder.
Strategy Pattern1 Design Patterns 1.Strategy Pattern How to design for flexibility?
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.
Statics in Depth Markus Götze FAU Erlangen Nürnberg Seminar Advanced C++ Programming
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.
Fall 2009ACS-3913 R McFadyen1 Singleton Problem: Exactly one instance of a certain object is required (this object is called a singleton). We must ensure.
Data Structures Topic #3. Today’s Agenda Ordered List ADTs –What are they –Discuss two different interpretations of an “ordered list” –Are manipulated.
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.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
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.
Builder A Creational Design Pattern A Presentation by Alex Bluhm And.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
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.
CSSE 374: Introduction to Gang of Four Design Patterns
Yet another Singleton? By The EPC (xpro.com.au) * Slide 1 Yet another singleton? Unique global objects play a part in nearly every program we write. Whether.
CPSC 372 John D. McGregor Module 4 Session 1 Design Patterns.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Singleton and Basic UML CS340100, NTHU Yoshi. What is UML Unified Modeling Language A standardized general-purpose modeling language in the field of software.
Mohammed Al-Dhelaan CSci 253 Object Oriented Design Instructor: Brad Taylor 06/02/2009 Factory Method Pattern.
Testing Extensible Design Patterns in OO Frameworks through Scenario Templates D.S. Sanders Software Verification & Validation.
Design Patterns Singleton & Factory Pattern Eriq Muhammad Adams J. Mail : | Blog :
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.
CPSC 871 John D. McGregor Module 5 Session 1 Design Patterns.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
Java Thread and Memory Model
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Findbugs Tin Bui-Huy September, Content What is bug? What is bug? What is Findbugs? What is Findbugs? How to use Findbugs? How to use Findbugs?
SEEM Java – Basic Introduction, Classes and Objects.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple listnodes Each listnode consists of Each listnode consists.
The PROXY Design Pattern Oleksandra Sopova Feb, 2014.
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
C:\Temp\Templates 4 5 Use This Main Program 6.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Singleton C ++ Design Patterns: Singleton in Detail Kutsyk Vasyl.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Programming with ANSI C ++
MPCS – Advanced java Programming
Design Patterns – Chocolate Factory (from Head First Design Patterns)
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Abstract Factory Pattern
Chapter 3: Using Methods, Classes, and Objects
This pointer, Dynamic memory allocation, Constructors and Destructor
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Programming Design Patterns
Singleton Pattern Pattern Name: Singleton Pattern Context
Singleton …there can be only one….
CS 350 – Software Design Singleton – Chapter 21
Java Programming Language
Design Patterns Imran Rashid CTO at ManiWeber Technologies.
5. Strategy, Singleton Patterns
Presentation transcript:

Singleton Duchenchuk Volodymyr Oksana Protsyk

2 /48

3 /48

What use is that? 4 /48

There are many objects we only need one of: -Caches -Dialog boxes -Objects that handle preferences and registry settings -Objects used for logging 5 /48

Can’t I just do this by convention or by global variables? 6 /48

Singleton is a convention for ensuring one and only one object is instantiated for a given class. Singleton Pattern gives global point of access, just like a global variable, but without the downsides. 7 /48

What downsides? 8 /48

An example: Global variable -> object is created when application begins. “The road to programming hell is paved with global variables” Steve McConnell 9 /48

public class Singleton { } 10 /48

public class Singleton { private Singleton() { } } 11 /48

public class Singleton { private Singleton() { } public static Singleton getInstance() { return new Singleton(); } 12 /48

public class Singleton { private static Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } 13 /48

public class Singleton { private static Singleton uniqueInstance; private Singleton() { } // other useful instance variables here public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } //other useful methods here } 14 /48

The Chocolate Factory All modern chocolate factories have computer controlled chocolate boilers. The job of the boiler is to take in chocolate and milk, bring them to a boil, and then pass them on to the next phase of making chocolate bars. 15 /48

public class ChocolateBoiler { private boolean empty; private boolean boiled; public boolean isEmpty() { return empty; } public boolean isBoiled() { return boiled; } //… } 16 /48

public ChocolateBoiler() { empty = true; boiled = false; } public void fill() { if (isEmpty()) { empty = false; boiled = false; //fill the boiler with a milk/chocolate mixture } 17 /48

public void boil() { if (!isEmpty() && !isBoiled()) { boiled = true; //bring the contents to a boil } public void drain() { if (!isEmpty() && isBoiled()) { empty = true; //drain the boiled milk and chocolate } 18 /48

How might things go wrong if more than one instance of ChocolateBoiler is created in an application? 19 /48

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it. 20 /48

21 /48

Dealing with multithreading public class Singleton { private static Singleton uniqueInstance; private Singleton() { } // other useful instance variables here public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } //other useful methods here } 22 /48

23 /48

Options to improve the code 1. Do nothing if the performance of getInstance() isn’t critical for your application 24 /48

Options to improve the code 2. Move to an eagerly created instance rather than a lazily created one public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return uniqueInstance; } 25 /48

Options to improve the code 3. Use “double-checked locking” to reduce the use of synchronization in getInstance() public class Singleton { private volatile static Singleton uniqueInstance; private Singleton() { } public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } 26 /48

Implementing Singleton (C++) class MyClass { public: static void doSomething(); private: static int _data; }; 27 /48

class Singleton { public: static Singleton* Instance() { if (!pInstance_) pInstance_ = new Singleton; return pInstance_; } private: Singleton(); Singleton(const Singleton&); static Singleton* pInstance_; }; // Implementation file Singleton.cpp Singleton* Singleton::pInstance_ = 0; 28 /48

//improved class Singleton { public: static Singleton& Instance();... private: Singleton(); Singleton(const Singleton&); Singleton& operator=(const Singleton&); ~Singleton();... }; 29 /48

Destroying the Singleton With the class definition we have destructor is never called. 30 /48

Meyers singleton Singleton& Singleton::Instance() { static Singleton obj; return obj; } 31 /48

A pseudo-C++ representation of the generated code by compiler Singleton& Singleton::Instance() { // Functions generated by the compiler extern void __ConstructSingleton(void* memory); extern void __DestroySingleton(); // Variables generated by the compiler static bool __initialized = false; // Buffer that holds the singleton static char __buffer[sizeof(Singleton)]; if (!__initialized) { // First call, construct object // Will invoke Singleton::Singleton // In the __buffer memory __ConstructSingleton(__buffer); // register destruction atexit(__DestroySingleton); __initialized = true; } return *reinterpret_cast (__buffer); } 32 /48

The Dead Reference Problem 33 /48 Three singletons: Keyboard, Display and Log.

34 /48 Keyboard Display Log

35 /48 Should I use Meyers Singleton?

Keyboard is constructed successfully 36 /48 Example Display fails to initialize Display's constructor creates Log

Local static objects are destroyed in the reverse order of their creation. Therefore, Log is destroyed before Keyboard. Log::Instance now returns a reference to the "shell" of a destroyed Log object. 37 /48

Improvement Let’s add static boolean member variable destroyed_ One function, one responsibility: Create, which effectively creates the Singleton OnDeadReference, which performs error handling Instance, which gives access to the unique Singleton object. 38 /48

static Singleton& Instance() { if (!pInstance_) { // Check for dead reference if (destroyed_) { OnDeadReference(); } else { // First call—initialize Create(); } return pInstance_; } 39 /48

// Create a new Singleton and store a // pointer to it in pInstance_ static void Create(); { static Singleton theInstance; pInstance_ = &theInstance; } 40 /48 // Gets called if dead reference detected static void OnDeadReference() { throw std::runtime_error("Dead Reference Detected"); } virtual ~Singleton() { pInstance_ = 0; destroyed_ = true; }

41 /48 But that doesn’t really fix the problem!

The Phoenix Singleton void Singleton::OnDeadReference() { // Obtain the shell of the destroyed singleton Create(); // Now pInstance_ points to the "ashes" of the singleton // - the raw memory that the singleton was seated in. // Create a new singleton at that address new(pInstance_) Singleton; // Queue this new object's destruction atexit(KillPhoenixSingleton); // Reset destroyed_ because we're back in business destroyed_ = false; } void Singleton::KillPhoenixSingleton() { pInstance_->~Singleton(); } 42 /48

Singletons with Longevity // Takes a reference to an object allocated with new and // the longevity of that object template void SetLongevity(T* pDynObject, unsigned int longevity); Each call to SetLongevity issues a call to atexit. Destruction of objects with lesser longevity takes place before destruction of objects with greater longevity. Destruction of objects with the same longevity follows the C++ rule: last built, first destroyed. 43 /48

Multithreading Singleton& Singleton::Instance() { if (!pInstance_) { Lock guard(mutex_); if (!pInstance_) { pInstance_ = new Singleton; } return *pInstance_; } 44 /48

In C++ 11 Meyers Singleton is thread-safety Singleton& Singleton::Instance() { static Singleton obj; return obj; } 45 /48

Summary It's relatively easy to protect Singleton against multiple instantiations. The most complicated problem is managing a singleton's lifetime, especially its destruction (C++). There are threading issues surrounding the Singleton design pattern. There is no “best” solution. 46 /48

References Head First Design Patterns by Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu 47 /48

Thanks for attention! 48 /48