Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface SingetonInterface {
- String someMethod(String someValue);
- }
- public class Singleton implements SingetonInterface {
- static {
- System.out.println("The Singleton class is loaded at this point.");
- }
- private static Singleton singletonInstance = new Singleton();
- private SingletonHelper singletonHelper = new SingletonHelper();
- private Singleton() { /* nothing */ }
- public static Singleton makeInstance() {
- return singletonInstance;
- }
- @Override
- public String someMethod(String someValue) {
- return singletonHelper.someMethod(someValue);
- }
- }
- public class SingletonHelper implements SingetonInterface {
- static {
- System.out.println("The SingletonHelper class is loaded at this point.");
- }
- SingletonHelper() {
- System.out.println("Lots of initialization here.");
- }
- @Override
- public String someMethod(String someValue) {
- // Real implementation here.
- return "Hello " + someValue + "!";
- }
- }
- public class SingletonUser {
- public static void main(String[] args) {
- System.out.println("Now in main method.");
- final Singleton instance1 = Singleton.makeInstance();
- System.out.println("Output: " + instance1.someMethod("World"));
- final Singleton instance2 = Singleton.makeInstance();
- System.out.println("Output: " + instance2.someMethod("Joe"));
- if (instance1 != instance2) {
- throw new IllegalStateException("It's not really a Singleton!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement