Advertisement
JeffGrigg

Nonreusable Singleton

Mar 3rd, 2018
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.58 KB | None | 0 0
  1. public interface SingetonInterface {
  2.     String someMethod(String someValue);
  3. }
  4.  
  5. public class Singleton implements SingetonInterface {
  6.  
  7.     static {
  8.         System.out.println("The Singleton class is loaded at this point.");
  9.     }
  10.  
  11.     private static Singleton singletonInstance = new Singleton();
  12.  
  13.     private SingletonHelper singletonHelper = new SingletonHelper();
  14.  
  15.     private Singleton() { /* nothing */ }
  16.  
  17.     public static Singleton makeInstance() {
  18.         return singletonInstance;
  19.     }
  20.  
  21.     @Override
  22.     public String someMethod(String someValue) {
  23.         return singletonHelper.someMethod(someValue);
  24.     }
  25.  
  26. }
  27.  
  28. public class SingletonHelper implements SingetonInterface {
  29.  
  30.     static {
  31.         System.out.println("The SingletonHelper class is loaded at this point.");
  32.     }
  33.  
  34.     SingletonHelper() {
  35.         System.out.println("Lots of initialization here.");
  36.     }
  37.  
  38.     @Override
  39.     public String someMethod(String someValue) {
  40.         // Real implementation here.
  41.         return "Hello " + someValue + "!";
  42.     }
  43.  
  44. }
  45.  
  46. public class SingletonUser {
  47.     public static void main(String[] args) {
  48.         System.out.println("Now in main method.");
  49.  
  50.         final Singleton instance1 = Singleton.makeInstance();
  51.         System.out.println("Output: " + instance1.someMethod("World"));
  52.  
  53.         final Singleton instance2 = Singleton.makeInstance();
  54.         System.out.println("Output: " + instance2.someMethod("Joe"));
  55.  
  56.         if (instance1 != instance2) {
  57.             throw new IllegalStateException("It's not really a Singleton!");
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement