Is Monostate the good cousin of the evil Singleton?

前端 未结 8 1639
梦如初夏
梦如初夏 2021-02-08 23:21

Singleton is definitely one of the most misused and abused patterns out there. Many of us have been infected with Singletonitis at one point or another. Curiously, its close c

8条回答
  •  清酒与你
    2021-02-08 23:42

    How about a class with a single instance, but without global access:

    public class SingleInstance
    {
        private static boolean exhausted = false;
    
        public SingleInstance()
        {
            if (exhausted)
            {
                throw new IllegalStateException("only one instance allowed");
            }
            exhausted = true;
    
            [...]
        }
    
        [...]
    }
    

    This avoids the problems of Singleton and MonoState, while it enforces and clearly communicates that there is only one instance.

提交回复
热议问题