SlideShare a Scribd company logo
1 of 15
Stéphane Ducasse 1
Stéphane Ducasse
stephane.ducasse@inria.fr
http://stephane.ducasse.free.fr/
Singleton
S.Ducasse 2
Singleton’s Intent
Ensure that a class has only
one instance, and provide a
global point of access to it
S.Ducasse 3
Problem / Solution
Problem:We want a class with a unique instance.
Solution:
Store the first time an instance is created and
return it each time a new instance is requested.
S.Ducasse 4
Example
db := DBConnect default.
db2 := DBConnect default.
db2 == db2
> true
Yes we get only one instance
S.Ducasse 5
Example
Object subclass: #DBConnect
instanceVariableNames: ''
classVariableNames: 'UniqueInstance'
poolDictionaries: ''
category: 'MyDB'
S.Ducasse 6
Implementation
NetworkManager class>>new
self error:‘should use uniqueInstance’
NetworkManager class>>uniqueInstance
UniqueInstance isNil
ifTrue: [ UniqueInstance := self basicNew initialize].
^UniqueInstance
S.Ducasse 7
Implementation Issues
Singletons may be accessed via a global variable
Pharo 1.1
Smalltalk points to SmalltalkImage current
Global access is good to get shorter expression
Smalltalk vs SmalltalkImage current
But this should be more the exception than the
rule
S.Ducasse 8
GlobalVariable or Class Method Access
GlobalVariable Access is dangerous: if we reassign
Smalltalk we lose all references to the current
SmalltalkImage
Class Method Access is better because it provides
a single access point.This class is responsible for
the singleton instance (creation, initialization,...).
S.Ducasse 9
Implementation Issues
Persistent Singleton: only one instance exists and
its identity does not change
Transient Singleton: only one instance exists at
any time, but that instance changes
Single Active Instance Singleton: a single instance
is active at any point in time, but other dormant
instances may also exist.
S.Ducasse 10
classVariable or class instance variable
classVariable (shared variable)
One singleton for a complete hierarchy
Class instance variable
One singleton per class
S.Ducasse 11
Access?
In Smalltalk we cannot prevent a client to send a
message (protected in C++).To prevent additional
creation we can redefine new/new:
DBConnect class>>new
self error:‘Class ‘, self name,‘ cannot create new instances’
11
S.Ducasse 12
Access using new: not good idea
DBConnect class>>new
^self uniqueInstance
The intent (uniqueness) is not clear anymore!
new is normally used to return newly created
instances.
Not intention revealing
S.Ducasse 13
new vs uniqueInstance
The difference between #new and #uniqueInstance
is that #new potentially initializes a new instance,
while #uniqueInstance only returns the unique
instance (there is no initialization)
Do we want to communicate that the class has a
singleton? new? defaultInstance? uniqueInstance?
S.Ducasse 14
Favor Instance Behavior
When a class should only have one instance, it is
tempting to define all its behavior at the class level.
This is not optimal:
Class behavior represents behavior of classes:“Ordinary
objects are used to model the real world. MetaObjects
describe these ordinary objects”
Now yes this may be tedious to type
DBConnect current reconnect
instead of DBConnect reconnect
What’s happens if later on an object can have
multiple instances?You have to change a lot of
S.Ducasse 15
Time and not Scope
Singleton is about time not access
time: only one instance is available at the same time
access: can’t you add an instance to refer to the object?
Singleton for access are as bad as global variables
Often we can avoid singleton by passing/referring
to the object instead of favoring a global access
point
It is worth to have one extra instance variable that
refers to the right object

More Related Content

Viewers also liked

Pharo Roadmap
Pharo RoadmapPharo Roadmap
Pharo Roadmap
ESUG
 

Viewers also liked (20)

Pharo tutorial at ECOOP 2013
Pharo tutorial at ECOOP 2013Pharo tutorial at ECOOP 2013
Pharo tutorial at ECOOP 2013
 
Pharo Roadmap
Pharo RoadmapPharo Roadmap
Pharo Roadmap
 
You Can’t Do That With Smalltalk!
You Can’t Do That With Smalltalk!You Can’t Do That With Smalltalk!
You Can’t Do That With Smalltalk!
 
Pharo Hands-on: 05 object model
Pharo Hands-on: 05 object modelPharo Hands-on: 05 object model
Pharo Hands-on: 05 object model
 
Haskell vs. F# vs. Scala
Haskell vs. F# vs. ScalaHaskell vs. F# vs. Scala
Haskell vs. F# vs. Scala
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesignStoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesign
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop 423-some designpatterns
Stoop 423-some designpatternsStoop 423-some designpatterns
Stoop 423-some designpatterns
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop 400 o-metaclassonly
Stoop 400 o-metaclassonlyStoop 400 o-metaclassonly
Stoop 400 o-metaclassonly
 
15 - Streams
15 - Streams15 - Streams
15 - Streams
 
07 bestpractice
07 bestpractice07 bestpractice
07 bestpractice
 
8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
Stoop 431-visitor
Stoop 431-visitorStoop 431-visitor
Stoop 431-visitor
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 

Similar to Stoop 432-singleton

4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)
The World of Smalltalk
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2
Mukul kumar Neal
 

Similar to Stoop 432-singleton (20)

9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)
 
9 - OOP - Smalltalk Classes (a)
9 - OOP - Smalltalk Classes (a)9 - OOP - Smalltalk Classes (a)
9 - OOP - Smalltalk Classes (a)
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
9 - OOP - Smalltalk Classes (c)
9 - OOP - Smalltalk Classes (c)9 - OOP - Smalltalk Classes (c)
9 - OOP - Smalltalk Classes (c)
 
Stoop 304-metaclasses
Stoop 304-metaclassesStoop 304-metaclasses
Stoop 304-metaclasses
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
JUC Europe 2015: Multi-Node Environment as a Jenkins Slave (Compound-Slave)
JUC Europe 2015: Multi-Node Environment as a Jenkins Slave (Compound-Slave)JUC Europe 2015: Multi-Node Environment as a Jenkins Slave (Compound-Slave)
JUC Europe 2015: Multi-Node Environment as a Jenkins Slave (Compound-Slave)
 
Debugging VisualWorks
Debugging VisualWorksDebugging VisualWorks
Debugging VisualWorks
 
Simpletest - A beginners guide
Simpletest - A beginners guideSimpletest - A beginners guide
Simpletest - A beginners guide
 
Design Patterns and Usage
Design Patterns and UsageDesign Patterns and Usage
Design Patterns and Usage
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Stoop 433-chain
Stoop 433-chainStoop 433-chain
Stoop 433-chain
 
4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)4 - OOP - Taste of Smalltalk (Tamagoshi)
4 - OOP - Taste of Smalltalk (Tamagoshi)
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2
 
Stoop 413-abstract classes
Stoop 413-abstract classesStoop 413-abstract classes
Stoop 413-abstract classes
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
 
TDD step patterns
TDD step patternsTDD step patterns
TDD step patterns
 

More from The World of Smalltalk (19)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
10 reflection
10 reflection10 reflection
10 reflection
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
06 debugging
06 debugging06 debugging
06 debugging
 
05 seaside
05 seaside05 seaside
05 seaside
 
04 idioms
04 idioms04 idioms
04 idioms
 
02 basics
02 basics02 basics
02 basics
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Stoop 432-singleton

  • 1. Stéphane Ducasse 1 Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Singleton
  • 2. S.Ducasse 2 Singleton’s Intent Ensure that a class has only one instance, and provide a global point of access to it
  • 3. S.Ducasse 3 Problem / Solution Problem:We want a class with a unique instance. Solution: Store the first time an instance is created and return it each time a new instance is requested.
  • 4. S.Ducasse 4 Example db := DBConnect default. db2 := DBConnect default. db2 == db2 > true Yes we get only one instance
  • 5. S.Ducasse 5 Example Object subclass: #DBConnect instanceVariableNames: '' classVariableNames: 'UniqueInstance' poolDictionaries: '' category: 'MyDB'
  • 6. S.Ducasse 6 Implementation NetworkManager class>>new self error:‘should use uniqueInstance’ NetworkManager class>>uniqueInstance UniqueInstance isNil ifTrue: [ UniqueInstance := self basicNew initialize]. ^UniqueInstance
  • 7. S.Ducasse 7 Implementation Issues Singletons may be accessed via a global variable Pharo 1.1 Smalltalk points to SmalltalkImage current Global access is good to get shorter expression Smalltalk vs SmalltalkImage current But this should be more the exception than the rule
  • 8. S.Ducasse 8 GlobalVariable or Class Method Access GlobalVariable Access is dangerous: if we reassign Smalltalk we lose all references to the current SmalltalkImage Class Method Access is better because it provides a single access point.This class is responsible for the singleton instance (creation, initialization,...).
  • 9. S.Ducasse 9 Implementation Issues Persistent Singleton: only one instance exists and its identity does not change Transient Singleton: only one instance exists at any time, but that instance changes Single Active Instance Singleton: a single instance is active at any point in time, but other dormant instances may also exist.
  • 10. S.Ducasse 10 classVariable or class instance variable classVariable (shared variable) One singleton for a complete hierarchy Class instance variable One singleton per class
  • 11. S.Ducasse 11 Access? In Smalltalk we cannot prevent a client to send a message (protected in C++).To prevent additional creation we can redefine new/new: DBConnect class>>new self error:‘Class ‘, self name,‘ cannot create new instances’ 11
  • 12. S.Ducasse 12 Access using new: not good idea DBConnect class>>new ^self uniqueInstance The intent (uniqueness) is not clear anymore! new is normally used to return newly created instances. Not intention revealing
  • 13. S.Ducasse 13 new vs uniqueInstance The difference between #new and #uniqueInstance is that #new potentially initializes a new instance, while #uniqueInstance only returns the unique instance (there is no initialization) Do we want to communicate that the class has a singleton? new? defaultInstance? uniqueInstance?
  • 14. S.Ducasse 14 Favor Instance Behavior When a class should only have one instance, it is tempting to define all its behavior at the class level. This is not optimal: Class behavior represents behavior of classes:“Ordinary objects are used to model the real world. MetaObjects describe these ordinary objects” Now yes this may be tedious to type DBConnect current reconnect instead of DBConnect reconnect What’s happens if later on an object can have multiple instances?You have to change a lot of
  • 15. S.Ducasse 15 Time and not Scope Singleton is about time not access time: only one instance is available at the same time access: can’t you add an instance to refer to the object? Singleton for access are as bad as global variables Often we can avoid singleton by passing/referring to the object instead of favoring a global access point It is worth to have one extra instance variable that refers to the right object