Are there any viable alternatives to the GOF Singleton Pattern?

后端 未结 16 1473
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 16:58

Let\'s face it. The Singleton Pattern is highly controversial topic with hordes programmers on both sides of the fence. There are those who feel like the Singleto

16条回答
  •  遥遥无期
    2020-11-29 17:53

    Monostate (described in Robert C. Martin's Agile Software Development) is an alternative to singleton. In this pattern the class's data are all static but the getters/setters are non-static.

    For example:

    public class MonoStateExample
    {
        private static int x;
    
        public int getX()
        {
            return x;
        }
    
        public void setX(int xVal)
        {
            x = xVal;
        }
    }
    
    public class MonoDriver
    {
        public static void main(String args[])
        {
            MonoStateExample m1 = new MonoStateExample();
            m1.setX(10);
    
            MonoStateExample m2 = new MonoStateExample();
            if(m1.getX() == m2.getX())
            {
                //singleton behavior
            }
        }
    }
    

    Monostate has similar behavior to singleton but does so in a way where the programmer is not necessarily aware of the fact that a singleton is being used.

提交回复
热议问题