Java/Design Pattern/Singleton Pattern

Материал из Java эксперт
Перейти к: навигация, поиск

A static class implementation of Singleton pattern

/*
The Design Patterns Java Companion
Copyright (C) 1998, by James W. Cooper
IBM Thomas J. Watson Research Center
*/
final class Spooler {
  
  static public void print(String s) {
    System.out.println(s);
  }
}

public class StaticSpool {
  public static void main(String argv[]) {
    Spooler.print("here it is");
  }
}





Singleton

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/** An example of a Singleton implementation in Java.
 * The Singleton design pattern is described in GOF; the idea is to ensure
 * that only one instance of the class will exist in a given application.
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Singleton.java,v 1.7 2004/02/09 03:33:58 ian Exp $
 */
public class Singleton {
  private static Singleton singleton = new Singleton();
  /** A private Constructor prevents any other class from instantiating. */
  private Singleton() {
  }
  /** Static "instance" method */
  public static Singleton getInstance() {
    return singleton;
  }
  // other methods protected by singleton-ness would be here...
  /** A simple demo method */
  public String demoMethod() {
    return "demo";
  }
}





Singleton Pattern 2

//[C] 2002 Sun Microsystems, Inc.---
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class RunSingletonPattern {
  public static void main(String[] arguments) {
    System.out.println("Example for Singleton pattern");
    System.out.println();
    System.out.println("This example will demonstrate the use of");
    System.out.println(" the Singleton pattern by creating two GUI");
    System.out.println(" editors, both of which will reference the");
    System.out.println(" same underlying history list.");
    System.out.println("Creating the first editor");
    System.out.println();
    SingletonGui editor1 = new SingletonGui();
    editor1.createGui();
    System.out.println("Creating the second editor");
    System.out.println();
    SingletonGui editor2 = new SingletonGui();
    editor2.createGui();
  }
}
class SingletonGui implements ActionListener {
  private JFrame mainFrame;
  private JTextArea display;
  private JButton newContact, newAppointment, undo, refresh, exit;
  private JPanel controlPanel, displayPanel;
  private static int historyCount;
  public void createGui() {
    mainFrame = new JFrame("Singleton Pattern Example");
    Container content = mainFrame.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
    displayPanel = new JPanel();
    display = new JTextArea(20, 60);
    display.setEditable(false);
    displayPanel.add(display);
    content.add(displayPanel);
    controlPanel = new JPanel();
    newContact = new JButton("Create contact");
    newAppointment = new JButton("Create appointment");
    undo = new JButton("Undo");
    refresh = new JButton("Refresh");
    exit = new JButton("Exit");
    controlPanel.add(newContact);
    controlPanel.add(newAppointment);
    controlPanel.add(undo);
    controlPanel.add(refresh);
    controlPanel.add(exit);
    content.add(controlPanel);
    newContact.addActionListener(this);
    newAppointment.addActionListener(this);
    undo.addActionListener(this);
    refresh.addActionListener(this);
    exit.addActionListener(this);
    mainFrame.addWindowListener(new WindowCloseManager());
    mainFrame.pack();
    mainFrame.setVisible(true);
  }
  public void refreshDisplay(String actionMessage) {
    display.setText(actionMessage + "\nCOMMAND HISTORY:\n"
        + HistoryList.getInstance().toString());
  }
  public void actionPerformed(ActionEvent evt) {
    Object originator = evt.getSource();
    if (originator == newContact) {
      addCommand(" New Contact");
    } else if (originator == newAppointment) {
      addCommand(" New Appointment");
    } else if (originator == undo) {
      undoCommand();
    } else if (originator == refresh) {
      refreshDisplay("");
    } else if (originator == exit) {
      exitApplication();
    }
  }
  private class WindowCloseManager extends WindowAdapter {
    public void windowClosing(WindowEvent evt) {
      exitApplication();
    }
  }
  private void addCommand(String message) {
    HistoryList.getInstance().addCommand((++historyCount) + message);
    refreshDisplay("Add Command: " + message);
  }
  private void undoCommand() {
    Object result = HistoryList.getInstance().undoCommand();
    historyCount--;
    refreshDisplay("Undo Command: " + result);
  }
  private void exitApplication() {
    System.exit(0);
  }
}
class HistoryList {
  private List history = Collections.synchronizedList(new ArrayList());
  private static HistoryList instance = new HistoryList();
  private HistoryList() {
  }
  public static HistoryList getInstance() {
    return instance;
  }
  public void addCommand(String command) {
    history.add(command);
  }
  public Object undoCommand() {
    return history.remove(history.size() - 1);
  }
  public String toString() {
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < history.size(); i++) {
      result.append("  ");
      result.append(history.get(i));
      result.append("\n");
    }
    return result.toString();
  }
}





Singleton pattern in Java 1

/*
The Design Patterns Java Companion
Copyright (C) 1998, by James W. Cooper
IBM Thomas J. Watson Research Center
*/
public class InstanceSpooler {
  static public void main(String argv[]) {
    Spooler pr1, pr2;
    //open one printer--this should always work
    System.out.println("Opening one spooler");
    pr1 = Spooler.Instance();
    if (pr1 != null)
      System.out.println("got 1 spooler");
    //try to open another printer --should fail
    System.out.println("Opening two spoolers");
    pr2 = Spooler.Instance();
    if (pr2 == null)
      System.out.println("no instance available");
    //fails because constructor is privatized
    //iSpooler pr3 = new iSpooler();
  }
}
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
  private Spooler() {
  }
  static public Spooler Instance() {
    if (!instance_flag) {
      instance_flag = true;
      return new Spooler();
    } else
      return null;
  }
  public void finalize() {
    instance_flag = false;
  }
}





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());
    }
  }
}





Singleton pattern in Java 3

/*
The Design Patterns Java Companion
Copyright (C) 1998, by James W. Cooper
IBM Thomas J. Watson Research Center
*/
class Printer {
  //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 Printer() 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 SinglePrinter {
  static public void main(String argv[]) {
    Printer pr1, pr2;
    //open one printer--this should always work
    System.out.println("Opening one printer");
    try {
      pr1 = new Printer();
    } catch (SingletonException e) {
      System.out.println(e.getMessage());
    }
    //try to open another printer --should fail
    System.out.println("Opening two printers");
    try {
      pr2 = new Printer();
    } catch (SingletonException e) {
      System.out.println(e.getMessage());
    }
  }
}