Is Monostate the good cousin of the evil Singleton

2019-03-20 14:15发布

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 cousin Monostate is less famous and less used. What is your opinion of Monostate? Good or just as evil? Is it a better alternative to using Singleton? Would you also discourage its use as you would with Singleton?

8条回答
小情绪 Triste *
2楼-- · 2019-03-20 14:52

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.

查看更多
干净又极端
3楼-- · 2019-03-20 14:58

The deal with Monostate is that you need to know less about the implementation of the object in order to use it. In other words you save a few keystrokes because you don't have to call the objects getInstance method ( Singleton s = Singleton::getInstance; s.Method(); ) to get a reference to the object, you simply use normal language constructs ( Monostate ms; ms.Method(); ). A fine line indeed.

Every programming langauge construct can be labeled evil because every programming language contrsuct can be abused.

When used reasonably, I see neither one being "evil" or "good."

查看更多
登录 后发表回答