Friday, 5 July 2019

Design Patterns | Modified Singleton Design pattern

Make a doubleton which returns the first object in even call of getInstance()  and second instance for odd call. See code below:

public class Doubleton {
      private Doubleton() {

      }

      private static int call = 0;
      private static Doubleton[] instances = { new Doubleton(), new Doubleton() };

      public static Doubleton getInstance() {
            return instances[call++ % 2];
      }

      public static void main(String[] args) {
            Doubleton d1 = Doubleton.getInstance();
            Doubleton d2 = Doubleton.getInstance();

            for (int i = 0; i < 10; i++) {
                  if (i % 2 == 0) {
                        System.out.println(d1 == Doubleton.getInstance());
                  } else {
                        System.out.println(d2 == Doubleton.getInstance());
                  }
            }
      }
}


See Thread Safe code below:

public class Doubleton {

      private static volatile Doubleton INSTANCE1;
      private static volatile Doubleton INSTANCE2;

      private static int call = 0;

      private Doubleton() {

      }
      public static Doubleton getInstance() {
            if (call++ % 2 == 0) {
                  if (INSTANCE1 == null) {
                        synchronized (Doubleton.class) {
                              if (INSTANCE1 == null) {
                                    INSTANCE1 = new Doubleton();
                              }
                        }
                  }
                  return INSTANCE1;
            } else {
                  if (INSTANCE2 == null) {
                        synchronized (Doubleton.class) {
                              if (INSTANCE2 == null) {
                                    INSTANCE2 = new Doubleton();
                              }
                        }
                  }
                  return INSTANCE2;
            }
      }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...