Singleton pattern in Java 2 : Singleton Pattern : Design Pattern : Java examples (example source code) Organized by topic

Java
C++
PHP
Java Home »  Design Pattern   » [  Singleton Pattern  ]  Screenshots 
 



Singleton pattern in Java 2



/*
The Design Patterns Java Companion

Copyright (C) 1998, by James W. Cooper

IBM Thomas J. Watson Research Center

*/
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 1 instance

  public Spooler() throws SingletonException {
    if (instance_flag)
      throw new SingletonException("Only one printer allowed");
    else
      instance_flag = true//set flag for 1 instance
    System.out.println("printer opened");
  }

  public void finalize() {
    instance_flag = false;
  }
}

class SingletonException extends RuntimeException {
  //new exception type for singleton classes
  public SingletonException() {
    super();
  }

  public SingletonException(String s) {
    super(s);
  }
}

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();
    catch (SingletonException e) {
      System.out.println(e.getMessage());
    }
  }
}

           
       
Related examples in the same category
1.  Singleton Pattern 2 Singleton Pattern 2
2.  Singleton
3.  Singleton pattern in Java 1
4.  A static class implementation of Singleton pattern A static class implementation of Singleton pattern
5.  Singleton pattern in Java 3 Singleton pattern in Java 3
























Home| Contact Us
Copyright 2003 - 04 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.