Download presentation
Presentation is loading. Please wait.
Published byAnna Perkins Modified over 8 years ago
1
Bjarne Stroustrup I have always wished that my computer would be as easy to use as my telephone. My wish has come true. I no longer know how to use my telephone.
2
Computer Science 313 – Advanced Programming Topics
3
Singleton Pattern System uses exactly 1 instance of the class Instantiates only 1 instance of the class Only lets program use single instance Does not restrict methods in any way Can change fields’ values also Use static method to access instance Get instance by calling method anywhere in program Can store a reference to instance in other classes… … but doing so considered bad style
4
Singleton Pattern Guides
5
Identifing a Singleton College president? Canisius College president? CSC313 Professor? TV Show theme song?
6
Common Themes in Singleton Elements always in Singleton class Static field holds instance Instance returned by public static method Singleton class usually includes… Private constructor limiting instantiation But class may include Protected constructor to allow subclassing Static method also serves as simple factory
7
How To Create Factory Singleton public class GameFact { private static GameFact me; protected GameFact() { } public static GameFact instance(int userAge){ if (me == null) { if (userAge < 13) me = new AnimatedGameFact(); else me = new RealisticGameFact(); } return me; } }
8
How Not To Create Singletons public class PrinterSpool { private static PrinterSpool me; private PrinterSpool() { } public static PrinterSpool instance() { if (me == null) { me = new PrinterSpool(); } return me; } }
9
Synchronization is Hard Synchronization very expensive Insures only 1 instance created Program must remain usable, however Easy upgrades not helpful if program unused 4 ways to hide costs of synchronization Each shifts where real costs occur Minimize costs with a good choice
10
When Method Rarely Called
12
When Instantiation is Cheap
14
For Use on Any JVM
16
On Modern (1.5+) JVMs
18
McCloud! Uniqueness leads to improvements Provide universal access Eliminate unneeded checks for errors Avoid creating large number of small objects Make space-time tradeoffs with confidence Can also make correctness easy Pretty easy to find object triggering error Ensure order of actions Prevents problems over which instance in charge
19
For Next Class Lab #5 on web/Angel & due week from Tues. Implements Decorator pattern & a factory You can choose the factory to implement Read article linked to from web/Angel page Describes how inlining works in Java Why getters & setters are cheap explained Shows how optimization cascades to generate really, really big improvements
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.