Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8, Design Patterns Singleton

Similar presentations


Presentation on theme: "Chapter 8, Design Patterns Singleton"— Presentation transcript:

1 Chapter 8, Design Patterns Singleton

2 A Pattern Taxonomy Pattern Behavioral Creational Structural Pattern
Composite Decorator Adapter Bridge Façade Proxy Iterator Visitor Command Observer Template Strategy Singleton Abstract Factory Builder Factory Prototype

3 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?

4 The Singleton Pattern - 2
Implementing singletons in Java Make the method getInstance public and static getInstance calls the constructor for the singleton pattern, which is not public, it is protected In this way, only one instance can be created

5 The Spooler as a Singleton
public class singleSpooler { static public void main(String argv[]) Spooler pr1, pr2; //open one printer--this should always work System.out.println("Opening one spooler"); try{ pr1 = new Spooler(); } catch (SingletonException e) {System.out.println(e.getMessage());} //try to open another printer --should fail System.out.println("Opening two spoolers"); try{ pr2 = new Spooler();

6 The Exception and the Spooler
public class SingletonException extends RuntimeException { //new exception type for singleton classes public SingletonException() { super(); } public SingletonException(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 SingletonException { if (instance_flag) throw new SingletonException("Only one printer allowed"); else instance_flag=true; //set flag for one instance System.out.println("printer opened");


Download ppt "Chapter 8, Design Patterns Singleton"

Similar presentations


Ads by Google