Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

design patterns - Why use singleton instead of static class?

When would a singleton actually be easier or better than a static class? It seems to me creating a singleton is just extra effort that's not actually needed, but I'm sure there is a good reason. Otherwise, they wouldn't be used, obviously.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One good reason for preferring a singleton over a static class (assuming you have no better patterns at your disposal ;) ), is swapping out one singleton instance with another.

For example, if I have a logging class like this:

public static class Logger {
    public static void Log(string s) { ... }
}

public class Client {
    public void DoSomething() {
        Logger.Log("DoSomething called");
    }
}

It works really well, but what if Logger writes things to a database, or writes output to the console. If you're writing tests, you probably don't want all those side-effects -- but since the log method is static, you can't do anything except.

Ok, so I want to hot-swap my Log method for testing. Go go gadget singleton!

public class Logger {
    private static Logger _instance;
    public static Logger Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Logger();
            return _instance;
        }
        set { _instance = value; }
    }
    protected Logger() { }
    public virtual void Log(string s) { ... }
}

public class Client {
    public void DoSomething() {
        Logger.Instance.Log("DoSomething called");
    }
}

So you can define a TestLogger : Logger with an empty Log method, then set an instance of your test logger to the singleton instance for tests. Presto! You can hotswap your logger implementation for tests or production without affecting client code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...