Download presentation
Presentation is loading. Please wait.
Published byDonald Carter Modified over 6 years ago
1
Design Patterns – Chocolate Factory (from Head First Design Patterns)
2
Scenario Automated chocolate bar maker Large chocolate boiler
General process: Fill with ingredients Boil the chocolate Drain the tank Chocolate goes to the next step Two data members empty boiled
3
Scenario (cont.) Method fill Method drain Method boil
If empty, empty = false, boiled = false Method drain If not empty and isboiled, empty = true Method boil If not empty and not boiled, boiled = true
4
Scenario (cont.) Possible issue: Software shouldn’t be able to think that there is / create two ChocolateBoiler instances Why not?
5
Scenario (cont.) Possible issue: Software shouldn’t be able to create two ChocolateBoiler instances Why not? There is only one physical ChocolateBoiler instance Steps could get done out of sync on two software instances (e.g. drain an empty boiler, two fills in a row)
6
Possible Solution Use Singleton pattern for ChocolateBoiler class
Only one ChocolateBoiler can be created Always access that ChocolateBoiler
7
public class ChocolateBoiler {
private boolean empty; private boolean boiled; private static ChocolateBoiler uniqueInstance; private ChocolateBoiler() { empty = true; boiled = false; } public static ChocolateBoiler getInstance () { if (uniqueInstance == null) { uniqueInstance = new ChocolateBoiler(); } return uniqueInstance; } }
8
Is this really a good solution? What possible problem can occur?
Hint: think about threads Three columns: Thread one Thread two Value of uniqueInstance
10
How to fix problem? Idea Make getInstance method synchronized
public static synchronized Singleton getInstance()
11
How to fix problem? Idea Make getInstance method synchronized
public static synchronized Singleton getInstance()
12
Problem with synchronization
Only used first time through Later synchronization overhead is totally unnecessary What can be done? Ignore problem (if not mission-critical) Use “eager creation” (static initialization of uniqueInstance) rather than “lazy creation” (creating at run-time, after code check for null instance) Double-checked locking – put synchronization only around body of ‘if’ statement
13
Singleton How to generalize Singleton pattern to support creation of up to N instances?
14
Singleton as an Anti-Pattern
Many criticisms of singleton have been put forth Issues Function like a global variable Mix creation and structure Difficult to test Overall: may want to look for alternatives, only use Singleton as a last resort
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.