Monday, March 5, 2012

How to write a singleton? (pros and contras)

A singleton for each situation and the pros and contras of it?


Lazy synchronized initialization

public final class Session 
  {
      private static Session instance;
 
      /** singleton */
      private Session() {}
 
      /** if you do not need synchronisation do not mark it as synchronized */
      public synchronized static Session getInstance() 
      {
          return (instance == null) ? instance = new Session() : instance;
      }
      /** your methods goes here... */
   }


PRO: can be initialized lazy the first time it is used
CONTRA: Singletons shall be avoid because they are hard to test and debug. Futher they contribute to less cohesive designs.


No Lazy initialization needed

public class Session 
  {
    private final static Session INSTANCE = new Session();

    private Session() {}

    public static Session getInstance() 
    { 
      return Session.INSTANCE; 
    }

    protected Object clone() 
    {
      throw new CloneNotSupportedException();
    }

    /** your methods goes here... */
  }

PRO: Immediate allocation of the needed resource
CONTRA: Needs "more" resource as nescessary + CONTRA from first case


No Lazy initialization needed (the elegant, modern way)

public enum Session 
   {
       INSTANCE;
       private int session;

       public int getSession() {
           return ++session;
       }

       /** your methods goes here... */
   }


PRO: Very simple, modern way. Immediate allocation of the needed resource
CONTRA: Needs "more" resource as nescessary + CONTRA from first case



😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†