SlideShare a Scribd company logo
Design Patterns 05/27/10 Week 1 : Introduction and Singleton Jon Simon [email_address]
Agenda Introduction to Design Patterns What is a Design Pattern Why Study Design Patterns History of Design Patterns The Gang of Four Tangent: Unit Testing The Book: Head First Design Patterns The Singleton Pattern Logger Example Lazy Instantiation Singleton vs. Static Variables Threading: Simple, Double-Checked, Eager Initialization Lab Inheritance Add Registry to Singleton Dependencies Unit Testing Articles
What is a Design Pattern? A problem that someone has already solved. A model or design to use as a guide More formally: “A proven solution to a common problem in a specified context."  Real World Examples Blueprint for a house Manufacturing 05/27/10
Why Study Design Patterns? Provides software developers a toolkit for handling problems that have already been solved. Provides a vocabulary that can be used amongst software developers. The Pattern Name itself helps establish a vocabulary Helps you  think  about how to solve a software problem. 05/27/10
History of Design Patterns Christopher Alexander (Civil Engineer) in 1977 wrote “ Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over,  without ever doing it the same way twice .” Each pattern has the same elements Pattern Name  – helps develop a catalog of common problems Problem  – describes when to apply the pattern. Describes problem and its context. Solution  – Elements that make up the design, their relationships, responsibilities, and collaborations. Consequences  – Results and trade-offs of applying the pattern 05/27/10
History (continued) In 1995,  the principles that Alexander established were applied to software design and architecture.  The result was the book: “ Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Also commonly known as “The Gang of Four”. 05/27/10
The Gang of Four Defines a Catalog of different design patterns. Three different types Creational  – “creating objects in a manner suitable for the situation” Structural  – “ease the design by identifying a simple way to realize relationships between entities” Behavorial  – “common communication patterns between objects” 05/27/10
The Gang of Four: Pattern Catalog 05/27/10 Patterns in red will be discussed in class. Creational Abstract Factory Builder Factory Method Prototype Singleton Structural Adapter Bridge Composite Decorator Façade Flyweight Proxy Behavioral Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor
How Design Patterns Solve Design Problems  From Gang of Four. Finding Appropriate Objects Determine Object Granularity Specify Object Interfaces Specifying Object Implementations Programming to an Interface, not an Implementation Encourage Reusability Inheritance versus Composition Delegation Support Extensibility Frameworks 05/27/10
Reality Problems with design early on It is sometimes very hard to “see” a design pattern. Not all requirements are known. A design that is applicable early on becomes obsolete. “ Paralysis by Analysis” Due to these realities, refactoring is inevitable! Question:  How do you mitigate the fact that you won’t have all of the design figured out? 05/27/10
Tangent: Unit Testing If you create unit tests early in the development cycle, then it will be easier to refactor later on when more requirements are known. As a developer, you will have more confidence to make good design adjustments. Good design adjustments may lead to better maintainability of the code! What happens if you do not have Unit Tests early on?  These statements may be heard: “  I am afraid to breaking something.” “ I know the right thing to do….but I am not going to do it because the system may become unstable.” You may incur “Technical Debt” if you do not refactor well 05/27/10
Unit Testing (cont) Unit Testing leads to easier Refactoring With easier Refactoring, you can take the risk of applying Design Patterns, even if it means changing a lot of code. Applying Design Patterns can decrease Technical Debt and improve the maintainability and extendibility of your system. Therefore…it  pays  to Unit Test! 05/27/10
Unit Testing: Final Thoughts Make unit testing part of the project culture. When creating a schedule, include unit testing in your estimates. Create your unit tests  before  you write the code. This helps define “Doneness” Helps you think about how software needs to be layered…it may actually lead to more refactoring! 05/27/10
Common Pitfall “ I just learned about Design Pattern XYZ. Let’s use it!” Reality : If you are going to use a Design Pattern, you should have a reason to do so.  The  software requirements  should really drive why you are going to use (or not use) a Design Pattern. 05/27/10
The Book “ Head First Design Patterns” Eric Freeman & Elisabeth Freeman Book is based on the Gang of Four design patterns. Easier to read. Examples are fun, but not necessarily “real world”. 05/27/10
Example: Logger What is wrong with this code? public class Logger { public Logger() { } public void LogMessage() { //Open File "log.txt" //Write Message //Close File } }
Example: Logger (cont) Since there is an external Shared Resource (“log.txt”), we want to closely control how we communicate with it. We shouldn’t have to create the Logger class every time we want to access this Shared Resource.  Is there any reason to? We need ONE.
Singleton GoF Definition: “The Singleton Pattern ensures a class has only  one instance , and provides a global point of access to it.” Best Uses Logging Caches Registry Settings Access External Resources  Printer Device Driver Database 05/27/10
Logger – as a Singleton public class Logger { private  Logger{}   private  static  Logger uniqueInstance; public  static  Logger getInstance() { if (uniqueInstance == null) uniqueInstance = new Logger(); return uniqueInstance; } } 05/27/10 Note the parameterless constructor See pg 173 in book
Lazy Instantiation Objects are only created when it is needed Helps control that we’ve created the Singleton just once. If it is resource intensive to set up, we want to do it once.  05/27/10
Singleton vs. Static Variables What if we had  not  created a Singleton for the Logger class??  Let’s pretend the Logger() constructor did a lot of setup. In our main program file, we had this code: public static Logger MyGlobalLogger = new Logger(); All of the Logger setup will occur regardless if we ever need to log or not.
Threading public class Singleton { private Singleton() {} private static Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) uniqueInstance = new Singleton(); return uniqueInstance; } } 05/27/10 What would happen if two different threads accessed this line at the same time?
Option #1: Simple Locking public class Singleton { private Singleton() {} private static Singleton uniqueInstance; public static Singleton getInstance() { synchronized(Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton(); } return uniqueInstance; } }
Option #2 – Double-Checked Locking public class Singleton { private Singleton() {} private  volatile  static Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) { synchronized(Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton(); } } return uniqueInstance; } } pg 182
Option #2  (C# Example) public class Singleton { private Singleton() {} private static object syncRoot = new Object(); private static volatile Singleton instance; public static Singleton Instance { get { if (instance == null) //first check { lock (syncRoot)  { if (instance == null) //second check instance = new Singleton(); } } return instance; } } } 05/27/10
Option #3: “Eager” Initialization public class Singleton { private Singleton() {} private static Singleton uniqueInstance = new Singleton() public static Singleton getInstance() { return uniqueInstance; } } 05/27/10 Instance is created the first time any member of the class is referenced.  Good to use if the application always creates; and if little overhead to create. Runtime guarantees that this is thread-safe pg 181
Lab #1: Turn a class into a Singleton public class Logger { public Logger() { } public void WriteLine(string text) { } public string ReadEntireLog() { return “Log Entries Here”; } } 05/27/10 Take this class and turn it into a Singleton.
Lab #1 Answer public class Logger { private Logger() { } private static Logger instance; public static Logger getInstance() { if (instance == null) instance = new Logger(); return instance; } //Functions . . .
Lab #2 public class BaseSingleton { private BaseSingleton() { } private static BaseSingleton instance; public static BaseSingleton getInstance() { if (instance == null) { instance = new BaseSingleton(); }  return instance; } //Some state variables protected int someInt; //Function is marked as virtual so that it can be overidden public void DoSomething() { someInt = 1; } } 05/27/10
Lab #2 (cont) public class SubClassSingleton extends BaseSingleton { private SubClassSingleton() { } public void DoSomething()  {  someInt = 2; } public void NewFunction() {  //new functionality here } } 05/27/10
Lab #2 (cont) Question #1:  What is wrong with the constructor for SubClassSingleton? 05/27/10
Lab #2 (cont) Here is the code that calls the Singleton: public class Main { public static void DoStuff() { 01  BaseSingleton.getInstance().DoSomething(); 02  SubClassSingleton.getInstance().DoSomething(); 03  SubClassSingleton.getInstance().NewFunction();  } } 05/27/10
Lab #2 (cont) Question #2:  For Line 01, what is the value of someInt after it is called? Question #3:  For Line 02, what is the value of someInt after it is called? Question #4:  What is wrong with Line 03? 05/27/10
Lab #2 Answers Question #1 : It will not compile.  The base constructor must be changed from private to protected. Question #2 – 1 Question #3 -  1 Even though we have overridden the base, it doesn’t matter. The base implementation is returned by getInstance(). Question 4 – It will not compile!
Inheritance Summary The sub-class can share state with the base class.  Now you have two objects that share state.  “ Gang of Four” recommends usages of a registry of Singletons.  The base class reads an environment variable to determine which Singleton to use. Bottom Line : Singletons and Inheritance do not mix well.  05/27/10
Add Registry to Singleton public class BaseSingleton { protected BaseSingleton() { } private static HashMap map = new HashMap(); public static BaseSingleton getInstance(String classname) { //First, attempt to get Singleton from HashMap BaseSingleton singleton = (BaseSingleton)map.get(classname); if (singleton != null) return singleton; else { //Singleton not found if (classname.Equals("SubClassSingleton")) singleton = new SubClassSingleton(); else ......  //Add singleton to HashMap so we can get it again map.put(classname, singleton); return singleton; }
SingletonRegistry Class Source http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=6 Describes a SingletonRegistry whose purpose is to store Singletons!  public static Singleton getInstance() { return (Singleton) SingletonRegistry.REGISTRY .getInstance(classname); }
Case Study: Dependencies public class Searcher { //Singleton Setup code Here public Collection FindCustomers(String criteria) { String conStr = GetConnectionFromRegistry(); OracleConnection conn = new OracleConnection(conStr); //Query database using criteria return (Collection of customers); } } 05/27/10
Case Study: Dependencies To search the database, the client code would need to do the following: Searcher.getInstance().FindCustomers(“some criteria”) What happens if we need to change the database to SQL Server?  Or change how we get the connection string?
Case Study: Dependencies The Singleton is  tightly coupled  to Oracle. If the database changed in the future, this object would need to be changed. It is also tightly coupled in how it retrieves the connection string. The Singleton hides object dependencies (Oracle and registry).  Anyone using the Singleton would need to inspect the internals to find out what is really going on. Possibly memory leak since the Singleton may hold onto the resource for an infinite amount of time. 05/27/10
Unit Testing There are many problems with unit testing a Singleton. Problem : If you are running multiple unit tests that accesses the same Singleton, the Singleton will retain state between unit tests.  This may lead to undesired results! Solution :  Use Reflection to get access to the private static instance variable. Then set it to null. This should be done at the end of each unit test. private static Singleton uniqueInstance; 05/27/10
Unit Testing  Other problems You want to unit test a method of a Singleton, but the method refers to other external resources. It is hard to inject a mock in this case. You are unit testing a method that does a lot of business logic.  One of the method calls is a Singleton that accesses an external resource. How can you replace the Singleton with a mock call? 05/27/10
Scott Densmore “Why Singletons are Evil” “… the dependencies in your design are hidden inside the code, and not visible by examining the interfaces of your classes and methods. You have to inspect the code to understand exactly what other objects your class uses. “ Singletons allow you to limit creation of your objects... you are mixing two different responsibilities into the same class.” “ Singletons promote tight coupling between classes.” “ Singletons carry state with them that last as long as the program lasts…Persistent state is the enemy of unit testing.” Source: http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx 05/27/10
Jeremy D. Miller “Chill out on the Singleton…” “ Using a stateful singleton opens yourself up to all kinds of threading issues. When you screw up threading safety you can create really wacky bugs that are devilishly hard to reproduce.  My best advice is to not use caching via static members until you absolutely have to for performance or resource limitation reasons.” Source: http://codebetter.com/blogs/jeremy.miller/archive/2005/08/04/130302.aspx 05/27/10
“ How to Decontaminate a Singleton” “ Define a Spring bean for each Singleton you use. For new DI-like implementations use the Spring bean as a wrapper that allows to access the functionality of the Singleton.” http://blog.rainer.eschen.name/2006/12/15/how-to-decontaminate-a-singleton/ 05/27/10
Comments from Others “ Sub-classing or creating mocks for Singletons is impossible (unless it implements an interface for its type)” “ It really should only be used in cases of classes for Constants for example.” “ Access to a singleton in an application must be serialized, which complicates multi-threading issues in applications hence introducing possible issues of thread locking.” 05/27/10
Comments from Others “ I had cases where I wanted to create a subclass, and the singleton kept referring to the superclass.” “ ..writing a good unit test was impossible because the class invoked a singleton, and there was no way to inject a fake.” “ Unit testing a singleton is not so much a problem as unit testing the other classes that use a singleton. They are bound so tightly that there is often no way to inject a fake (or mock) version of the singleton class. In some cases you can live with that, but in other cases, such as when the singleton accesses an external resource like a database, it's intolerable for a unit test.” 05/27/10
Other Useful Articles Singleton Explained http://c2.com/cgi/wiki?SingletonPattern http://www.oodesign.com/singleton-pattern.html Unit Testing  http://imistaken.blogspot.com/2009/11/unit-testing-singletons.html http://weblogs.asp.net/okloeten/archive/2004/08/19/217182.aspx
SUMMARY Pattern Name  – Singleton Problem  – Ensures one instance of an object and global access to it. Solution Hide the constructor Use static method to return one instance of the object Consequences Lazy Instantiation Threading Inheritance issues Hides dependencies Difficult unit testing 05/27/10
Ad

More Related Content

What's hot (20)

Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Composite pattern
Composite patternComposite pattern
Composite pattern
Shakil Ahmed
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Android Fragment
Android FragmentAndroid Fragment
Android Fragment
Kan-Han (John) Lu
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
Scott Leberknight
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
Andreas Enbohm
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
Anjan Kumar Bollam
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | Edureka
Edureka!
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
Dmitry Buzdin
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
Rana Muhammad Asif
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
Lilia Sfaxi
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
Coding Academy
 
Facade pattern
Facade patternFacade pattern
Facade pattern
JAINIK PATEL
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
Andreas Enbohm
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | Edureka
Edureka!
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
Lilia Sfaxi
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
Coding Academy
 

Viewers also liked (20)

Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
Jonathan Simon
 
MVC and Other Design Patterns
MVC and Other Design PatternsMVC and Other Design Patterns
MVC and Other Design Patterns
Jonathan Simon
 
Factory and Abstract Factory
Factory and Abstract FactoryFactory and Abstract Factory
Factory and Abstract Factory
Jonathan Simon
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
Jonathan Simon
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
Jonathan Simon
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in php
David Stockton
 
Design patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAMDesign patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAM
Nishant Shrivastava
 
Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012
Aaron Saray
 
Introduction to design
Introduction to designIntroduction to design
Introduction to design
Chris Snider
 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
ppd1961
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
Fabien Potencier
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
Michael Heron
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
paramisoft
 
Singleton class in Java
Singleton class in JavaSingleton class in Java
Singleton class in Java
Rahul Sharma
 
Construction Management in Developing Countries, Lecture 8
Construction Management in Developing Countries, Lecture 8Construction Management in Developing Countries, Lecture 8
Construction Management in Developing Countries, Lecture 8
Hari Krishna Shrestha
 
Code & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignCode & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven Design
Frank Levering
 
Domain Driven Design Development Spring Portfolio
Domain Driven Design Development Spring PortfolioDomain Driven Design Development Spring Portfolio
Domain Driven Design Development Spring Portfolio
Srini Penchikala
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
Manoj Kumar
 
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
Cavanghetboi Cavangboihet
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
Jonathan Simon
 
MVC and Other Design Patterns
MVC and Other Design PatternsMVC and Other Design Patterns
MVC and Other Design Patterns
Jonathan Simon
 
Factory and Abstract Factory
Factory and Abstract FactoryFactory and Abstract Factory
Factory and Abstract Factory
Jonathan Simon
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
Jonathan Simon
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
Jonathan Simon
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in php
David Stockton
 
Design patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAMDesign patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAM
Nishant Shrivastava
 
Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012
Aaron Saray
 
Introduction to design
Introduction to designIntroduction to design
Introduction to design
Chris Snider
 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
ppd1961
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
Fabien Potencier
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
Michael Heron
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
paramisoft
 
Singleton class in Java
Singleton class in JavaSingleton class in Java
Singleton class in Java
Rahul Sharma
 
Construction Management in Developing Countries, Lecture 8
Construction Management in Developing Countries, Lecture 8Construction Management in Developing Countries, Lecture 8
Construction Management in Developing Countries, Lecture 8
Hari Krishna Shrestha
 
Code & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignCode & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven Design
Frank Levering
 
Domain Driven Design Development Spring Portfolio
Domain Driven Design Development Spring PortfolioDomain Driven Design Development Spring Portfolio
Domain Driven Design Development Spring Portfolio
Srini Penchikala
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
Manoj Kumar
 
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
Cavanghetboi Cavangboihet
 
Ad

Similar to Introduction to Design Patterns and Singleton (20)

JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
ChengHui Weng
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
Lalit Kale
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
Design patterns
Design patternsDesign patterns
Design patterns
mudabbirwarsi
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
C Meenakshi Meyyappan
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
Steven Smith
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
Prageeth Sandakalum
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad idea
PVS-Studio
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
Sandeep Chawla
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
James Phillips
 
Creational pattern
Creational patternCreational pattern
Creational pattern
Himanshu
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Rafael Coutinho
 
Design patterns
Design patternsDesign patterns
Design patterns
Jason Austin
 
Sda 8
Sda   8Sda   8
Sda 8
AmberMughal5
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
Ravi Mone
 
What is design pattern
What is design patternWhat is design pattern
What is design pattern
Md.Shohel Rana ( M.Sc in CSE Khulna University of Engineering & Technology (KUET))
 
Patterns for the People
Patterns for the PeoplePatterns for the People
Patterns for the People
Kevlin Henney
 
Ad

Recently uploaded (20)

Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 

Introduction to Design Patterns and Singleton

  • 1. Design Patterns 05/27/10 Week 1 : Introduction and Singleton Jon Simon [email_address]
  • 2. Agenda Introduction to Design Patterns What is a Design Pattern Why Study Design Patterns History of Design Patterns The Gang of Four Tangent: Unit Testing The Book: Head First Design Patterns The Singleton Pattern Logger Example Lazy Instantiation Singleton vs. Static Variables Threading: Simple, Double-Checked, Eager Initialization Lab Inheritance Add Registry to Singleton Dependencies Unit Testing Articles
  • 3. What is a Design Pattern? A problem that someone has already solved. A model or design to use as a guide More formally: “A proven solution to a common problem in a specified context." Real World Examples Blueprint for a house Manufacturing 05/27/10
  • 4. Why Study Design Patterns? Provides software developers a toolkit for handling problems that have already been solved. Provides a vocabulary that can be used amongst software developers. The Pattern Name itself helps establish a vocabulary Helps you think about how to solve a software problem. 05/27/10
  • 5. History of Design Patterns Christopher Alexander (Civil Engineer) in 1977 wrote “ Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice .” Each pattern has the same elements Pattern Name – helps develop a catalog of common problems Problem – describes when to apply the pattern. Describes problem and its context. Solution – Elements that make up the design, their relationships, responsibilities, and collaborations. Consequences – Results and trade-offs of applying the pattern 05/27/10
  • 6. History (continued) In 1995, the principles that Alexander established were applied to software design and architecture. The result was the book: “ Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Also commonly known as “The Gang of Four”. 05/27/10
  • 7. The Gang of Four Defines a Catalog of different design patterns. Three different types Creational – “creating objects in a manner suitable for the situation” Structural – “ease the design by identifying a simple way to realize relationships between entities” Behavorial – “common communication patterns between objects” 05/27/10
  • 8. The Gang of Four: Pattern Catalog 05/27/10 Patterns in red will be discussed in class. Creational Abstract Factory Builder Factory Method Prototype Singleton Structural Adapter Bridge Composite Decorator Façade Flyweight Proxy Behavioral Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor
  • 9. How Design Patterns Solve Design Problems From Gang of Four. Finding Appropriate Objects Determine Object Granularity Specify Object Interfaces Specifying Object Implementations Programming to an Interface, not an Implementation Encourage Reusability Inheritance versus Composition Delegation Support Extensibility Frameworks 05/27/10
  • 10. Reality Problems with design early on It is sometimes very hard to “see” a design pattern. Not all requirements are known. A design that is applicable early on becomes obsolete. “ Paralysis by Analysis” Due to these realities, refactoring is inevitable! Question: How do you mitigate the fact that you won’t have all of the design figured out? 05/27/10
  • 11. Tangent: Unit Testing If you create unit tests early in the development cycle, then it will be easier to refactor later on when more requirements are known. As a developer, you will have more confidence to make good design adjustments. Good design adjustments may lead to better maintainability of the code! What happens if you do not have Unit Tests early on? These statements may be heard: “ I am afraid to breaking something.” “ I know the right thing to do….but I am not going to do it because the system may become unstable.” You may incur “Technical Debt” if you do not refactor well 05/27/10
  • 12. Unit Testing (cont) Unit Testing leads to easier Refactoring With easier Refactoring, you can take the risk of applying Design Patterns, even if it means changing a lot of code. Applying Design Patterns can decrease Technical Debt and improve the maintainability and extendibility of your system. Therefore…it pays to Unit Test! 05/27/10
  • 13. Unit Testing: Final Thoughts Make unit testing part of the project culture. When creating a schedule, include unit testing in your estimates. Create your unit tests before you write the code. This helps define “Doneness” Helps you think about how software needs to be layered…it may actually lead to more refactoring! 05/27/10
  • 14. Common Pitfall “ I just learned about Design Pattern XYZ. Let’s use it!” Reality : If you are going to use a Design Pattern, you should have a reason to do so. The software requirements should really drive why you are going to use (or not use) a Design Pattern. 05/27/10
  • 15. The Book “ Head First Design Patterns” Eric Freeman & Elisabeth Freeman Book is based on the Gang of Four design patterns. Easier to read. Examples are fun, but not necessarily “real world”. 05/27/10
  • 16. Example: Logger What is wrong with this code? public class Logger { public Logger() { } public void LogMessage() { //Open File "log.txt" //Write Message //Close File } }
  • 17. Example: Logger (cont) Since there is an external Shared Resource (“log.txt”), we want to closely control how we communicate with it. We shouldn’t have to create the Logger class every time we want to access this Shared Resource. Is there any reason to? We need ONE.
  • 18. Singleton GoF Definition: “The Singleton Pattern ensures a class has only one instance , and provides a global point of access to it.” Best Uses Logging Caches Registry Settings Access External Resources Printer Device Driver Database 05/27/10
  • 19. Logger – as a Singleton public class Logger { private Logger{} private static Logger uniqueInstance; public static Logger getInstance() { if (uniqueInstance == null) uniqueInstance = new Logger(); return uniqueInstance; } } 05/27/10 Note the parameterless constructor See pg 173 in book
  • 20. Lazy Instantiation Objects are only created when it is needed Helps control that we’ve created the Singleton just once. If it is resource intensive to set up, we want to do it once. 05/27/10
  • 21. Singleton vs. Static Variables What if we had not created a Singleton for the Logger class?? Let’s pretend the Logger() constructor did a lot of setup. In our main program file, we had this code: public static Logger MyGlobalLogger = new Logger(); All of the Logger setup will occur regardless if we ever need to log or not.
  • 22. Threading public class Singleton { private Singleton() {} private static Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) uniqueInstance = new Singleton(); return uniqueInstance; } } 05/27/10 What would happen if two different threads accessed this line at the same time?
  • 23. Option #1: Simple Locking public class Singleton { private Singleton() {} private static Singleton uniqueInstance; public static Singleton getInstance() { synchronized(Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton(); } return uniqueInstance; } }
  • 24. Option #2 – Double-Checked Locking public class Singleton { private Singleton() {} private volatile static Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) { synchronized(Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton(); } } return uniqueInstance; } } pg 182
  • 25. Option #2 (C# Example) public class Singleton { private Singleton() {} private static object syncRoot = new Object(); private static volatile Singleton instance; public static Singleton Instance { get { if (instance == null) //first check { lock (syncRoot) { if (instance == null) //second check instance = new Singleton(); } } return instance; } } } 05/27/10
  • 26. Option #3: “Eager” Initialization public class Singleton { private Singleton() {} private static Singleton uniqueInstance = new Singleton() public static Singleton getInstance() { return uniqueInstance; } } 05/27/10 Instance is created the first time any member of the class is referenced. Good to use if the application always creates; and if little overhead to create. Runtime guarantees that this is thread-safe pg 181
  • 27. Lab #1: Turn a class into a Singleton public class Logger { public Logger() { } public void WriteLine(string text) { } public string ReadEntireLog() { return “Log Entries Here”; } } 05/27/10 Take this class and turn it into a Singleton.
  • 28. Lab #1 Answer public class Logger { private Logger() { } private static Logger instance; public static Logger getInstance() { if (instance == null) instance = new Logger(); return instance; } //Functions . . .
  • 29. Lab #2 public class BaseSingleton { private BaseSingleton() { } private static BaseSingleton instance; public static BaseSingleton getInstance() { if (instance == null) { instance = new BaseSingleton(); } return instance; } //Some state variables protected int someInt; //Function is marked as virtual so that it can be overidden public void DoSomething() { someInt = 1; } } 05/27/10
  • 30. Lab #2 (cont) public class SubClassSingleton extends BaseSingleton { private SubClassSingleton() { } public void DoSomething() { someInt = 2; } public void NewFunction() { //new functionality here } } 05/27/10
  • 31. Lab #2 (cont) Question #1: What is wrong with the constructor for SubClassSingleton? 05/27/10
  • 32. Lab #2 (cont) Here is the code that calls the Singleton: public class Main { public static void DoStuff() { 01 BaseSingleton.getInstance().DoSomething(); 02 SubClassSingleton.getInstance().DoSomething(); 03 SubClassSingleton.getInstance().NewFunction(); } } 05/27/10
  • 33. Lab #2 (cont) Question #2: For Line 01, what is the value of someInt after it is called? Question #3: For Line 02, what is the value of someInt after it is called? Question #4: What is wrong with Line 03? 05/27/10
  • 34. Lab #2 Answers Question #1 : It will not compile. The base constructor must be changed from private to protected. Question #2 – 1 Question #3 - 1 Even though we have overridden the base, it doesn’t matter. The base implementation is returned by getInstance(). Question 4 – It will not compile!
  • 35. Inheritance Summary The sub-class can share state with the base class. Now you have two objects that share state. “ Gang of Four” recommends usages of a registry of Singletons. The base class reads an environment variable to determine which Singleton to use. Bottom Line : Singletons and Inheritance do not mix well. 05/27/10
  • 36. Add Registry to Singleton public class BaseSingleton { protected BaseSingleton() { } private static HashMap map = new HashMap(); public static BaseSingleton getInstance(String classname) { //First, attempt to get Singleton from HashMap BaseSingleton singleton = (BaseSingleton)map.get(classname); if (singleton != null) return singleton; else { //Singleton not found if (classname.Equals("SubClassSingleton")) singleton = new SubClassSingleton(); else ...... //Add singleton to HashMap so we can get it again map.put(classname, singleton); return singleton; }
  • 37. SingletonRegistry Class Source http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=6 Describes a SingletonRegistry whose purpose is to store Singletons! public static Singleton getInstance() { return (Singleton) SingletonRegistry.REGISTRY .getInstance(classname); }
  • 38. Case Study: Dependencies public class Searcher { //Singleton Setup code Here public Collection FindCustomers(String criteria) { String conStr = GetConnectionFromRegistry(); OracleConnection conn = new OracleConnection(conStr); //Query database using criteria return (Collection of customers); } } 05/27/10
  • 39. Case Study: Dependencies To search the database, the client code would need to do the following: Searcher.getInstance().FindCustomers(“some criteria”) What happens if we need to change the database to SQL Server? Or change how we get the connection string?
  • 40. Case Study: Dependencies The Singleton is tightly coupled to Oracle. If the database changed in the future, this object would need to be changed. It is also tightly coupled in how it retrieves the connection string. The Singleton hides object dependencies (Oracle and registry). Anyone using the Singleton would need to inspect the internals to find out what is really going on. Possibly memory leak since the Singleton may hold onto the resource for an infinite amount of time. 05/27/10
  • 41. Unit Testing There are many problems with unit testing a Singleton. Problem : If you are running multiple unit tests that accesses the same Singleton, the Singleton will retain state between unit tests. This may lead to undesired results! Solution : Use Reflection to get access to the private static instance variable. Then set it to null. This should be done at the end of each unit test. private static Singleton uniqueInstance; 05/27/10
  • 42. Unit Testing Other problems You want to unit test a method of a Singleton, but the method refers to other external resources. It is hard to inject a mock in this case. You are unit testing a method that does a lot of business logic. One of the method calls is a Singleton that accesses an external resource. How can you replace the Singleton with a mock call? 05/27/10
  • 43. Scott Densmore “Why Singletons are Evil” “… the dependencies in your design are hidden inside the code, and not visible by examining the interfaces of your classes and methods. You have to inspect the code to understand exactly what other objects your class uses. “ Singletons allow you to limit creation of your objects... you are mixing two different responsibilities into the same class.” “ Singletons promote tight coupling between classes.” “ Singletons carry state with them that last as long as the program lasts…Persistent state is the enemy of unit testing.” Source: http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx 05/27/10
  • 44. Jeremy D. Miller “Chill out on the Singleton…” “ Using a stateful singleton opens yourself up to all kinds of threading issues. When you screw up threading safety you can create really wacky bugs that are devilishly hard to reproduce. My best advice is to not use caching via static members until you absolutely have to for performance or resource limitation reasons.” Source: http://codebetter.com/blogs/jeremy.miller/archive/2005/08/04/130302.aspx 05/27/10
  • 45. “ How to Decontaminate a Singleton” “ Define a Spring bean for each Singleton you use. For new DI-like implementations use the Spring bean as a wrapper that allows to access the functionality of the Singleton.” http://blog.rainer.eschen.name/2006/12/15/how-to-decontaminate-a-singleton/ 05/27/10
  • 46. Comments from Others “ Sub-classing or creating mocks for Singletons is impossible (unless it implements an interface for its type)” “ It really should only be used in cases of classes for Constants for example.” “ Access to a singleton in an application must be serialized, which complicates multi-threading issues in applications hence introducing possible issues of thread locking.” 05/27/10
  • 47. Comments from Others “ I had cases where I wanted to create a subclass, and the singleton kept referring to the superclass.” “ ..writing a good unit test was impossible because the class invoked a singleton, and there was no way to inject a fake.” “ Unit testing a singleton is not so much a problem as unit testing the other classes that use a singleton. They are bound so tightly that there is often no way to inject a fake (or mock) version of the singleton class. In some cases you can live with that, but in other cases, such as when the singleton accesses an external resource like a database, it's intolerable for a unit test.” 05/27/10
  • 48. Other Useful Articles Singleton Explained http://c2.com/cgi/wiki?SingletonPattern http://www.oodesign.com/singleton-pattern.html Unit Testing http://imistaken.blogspot.com/2009/11/unit-testing-singletons.html http://weblogs.asp.net/okloeten/archive/2004/08/19/217182.aspx
  • 49. SUMMARY Pattern Name – Singleton Problem – Ensures one instance of an object and global access to it. Solution Hide the constructor Use static method to return one instance of the object Consequences Lazy Instantiation Threading Inheritance issues Hides dependencies Difficult unit testing 05/27/10

Editor's Notes

  • #4: 13 November 2008
  • #5: 13 November 2008
  • #6: 13 November 2008
  • #7: 13 November 2008
  • #10: 13 November 2008
  • #11: 13 November 2008
  • #12: 13 November 2008
  • #13: 13 November 2008
  • #15: 13 November 2008
  • #16: 13 November 2008
  • #20: 13 November 2008
  • #23: Result : Each thread could create a Singleton. This is a violation of the Singleton pattern!
  • #26: 13 November 2008
  • #36: 13 November 2008
  • #39: 13 November 2008
  • #41: 13 November 2008
  • #44: 13 November 2008