Using UML Patterns and Java ObjectOriented Software Engineering
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 8, Design Patterns Singleton
A Pattern Taxonomy Pattern Structural Pattern Behavioral Pattern Creational Pattern Composite Decorator Adapter Bridge Façade Proxy Iterator Visitor Command Observer Template Strategy Singleton Abstract Factory Builder Factory Prototype Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 2
The Singleton Pattern - 1 • This is perhaps the easiest design patter • The goal is to insure that only one instance of an object is possible • Give some applications where you think the singleton design pattern would be useful?
The Singleton Pattern - 2 • Implementing singletons in Java – Make the method get. Instance public and static – get. Instance calls the constructor for the singleton pattern, which is not public, it is protected – In this way, only one instance can be created
The Spooler as a Singleton public class single. Spooler { static public void main(String argv[]) { Spooler pr 1, pr 2; //open one printer--this should always work System. out. println("Opening one spooler"); try{ pr 1 = new Spooler(); } catch (Singleton. Exception e) {System. out. println(e. get. Message()); } //try to open another printer --should fail System. out. println("Opening two spoolers"); try{ pr 2 = new Spooler(); } catch (Singleton. Exception e) {System. out. println(e. get. Message()); } } }
The Exception and the Spooler public class Singleton. Exception extends Runtime. Exception { //new exception type for singleton classes public Singleton. Exception() { super(); } public Singleton. Exception(String s) { super(s); } } public class Spooler { //this is a prototype for a printer-spooler class //such that only one instance can ever exist static boolean instance_flag = false; //true if one instance public Spooler() throws Singleton. Exception { if (instance_flag) throw new Singleton. Exception("Only one printer allowed"); else instance_flag=true; //set flag for one instance System. out. println("printer opened"); } }
- Slides: 6