Java Tutorial/Design Pattern/Singleton — различия между версиями

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

Текущая версия на 05:02, 1 июня 2010

Basic Singleton

public class BasicSingleton {
  static Singleton s1 = null, s2 = null;
  public static void main(String[] args) {
    s1 = Singleton.getInstance();
    s2 = Singleton.getInstance();
  }
}
class Singleton {
  private static Singleton mySingleton = null;
  private Singleton() {
  }
  public static synchronized Singleton getInstance() {
    if (null == mySingleton) {
      mySingleton = new Singleton();
      System.out.println(mySingleton.toString());
    } else {
      System.out.println(mySingleton.toString());
    }
    return mySingleton;
  }
}





Singleton Factory

class Product {
}
interface Factory {
  Product create();
}
class SingletonFactory implements Factory {
  private Product product;
  public synchronized Product create() {
    if (this.product == null) {
      product = new Product();
    }
    return product;
  }
}
public class FactoryDemo {
  public static void main(String[] args) {
    Factory factory = new SingletonFactory();
    Product p1 = factory.create();
    for (int i = 0; i < 100; i++) {
      if (factory.create() != p1) {
        System.out.println("Factory returned another instance of Product!");
      }
    }
  }
}





Singleton test

public class TestSingleton {
  public static void main(String args[]) {
    Database database;
    database = Database.getInstance("products");
    System.out.println("This is the " + database.getName() + " database.");
    database = Database.getInstance("employees");
    System.out.println("This is the " + database.getName() + " database.");
  }
}
class Database {
  private static Database singleObject;
  private int record;
  private String name;
  private Database(String n) {
    name = n;
    record = 0;
  }
  public static synchronized Database getInstance(String n) {
    if (singleObject == null) {
      singleObject = new Database(n);
    }
    return singleObject;
  }
  public void editRecord(String operation) {
    System.out.println("Performing a " + operation + " operation on record " + record
        + " in database " + name);
  }
  public String getName() {
    return name;
  }
}





Synchronized Singleton

public class TestSingletonSynchronized implements java.lang.Runnable {
  Thread thread;
  public static void main(String args[]) {
    TestSingletonSynchronized t = new TestSingletonSynchronized();
  }
  public TestSingletonSynchronized() {
    SynchronizedData database = SynchronizedData.getInstance("products");
    thread = new Thread(this, "second");
    thread.start();
    System.out.println("This is the " + database.getName() + " database.");
  }
  public void run() {
    SynchronizedData database = SynchronizedData
        .getInstance("employees");
    System.out.println("This is the " + database.getName() + " database.");
  }
}
class SynchronizedData {
  private static SynchronizedData singleObject;
  private int record;
  private String name;
  private SynchronizedData(String n) {
    name = n;
    record = 0;
  }
  public static synchronized SynchronizedData getInstance(String n) {
    if (singleObject == null) {
      singleObject = new SynchronizedData(n);
    }
    return singleObject;
  }
  public void edit(String operation) {
    System.out.println("Performing a " + operation + " operation on record "
        + record + " in database " + name);
  }
  public String getName() {
    return name;
  }
}





The Singleton design pattern: you can never instantiate more than one.

Singleton provides a global access point
A singleton often has the characteristics of a registry or lookup service.
A singleton prevents the client programmer from having any way to create an object except the ways you provide. 
You must make all constructors private.
You must create at least one constructor to prevent the compiler from synthesizing a default constructor.
You provide access through public methods. 
Making the class final prevents cloning. 

final class Singleton {
  private static Singleton s = new Singleton(47);
  private int i;
  private Singleton(int x) {
    i = x;
  }
  public static Singleton getReference() {
    return s;
  }
  public int getValue() {
    return i;
  }
  public void setValue(int x) {
    i = x;
  }
}
public class SingletonPattern {
  public static void main(String[] args) {
    Singleton s = Singleton.getReference();
    String result = "" + s.getValue();
    System.out.println(result);
    Singleton s2 = Singleton.getReference();
    s2.setValue(9);
    result = "" + s.getValue();
    System.out.println(result);
  }
}