为什么使用singleton而不是静态类? [英] Why use singleton instead of static class?

查看:164
本文介绍了为什么使用singleton而不是静态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单例实际上比静态类更容易还是更好?在我看来,创建一个单身是只是额外的努力,实际上不需要,但我敢肯定有一个很好的理由。

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.

推荐答案

一个很好的理由是喜欢单例对静态类(假设你

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");
    }
}

它工作得很好,但如果Logger写东西到数据库,或将输出写入控制台。如果你正在编写测试,你可能不想要所有的副作用 - 但由于日志方法是静态的,你不能做任何事情,除了。

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,所以我想热交换我的Log方法进行测试。 Go go gadget singleton!

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");
    }
}

因此,您可以定义 TestLogger:Logger 使用空的 Log 方法,然后将测试记录器的实例设置为单例实例进行测试。 Presto!您可以在不影响客户端代码的情况下热交换测试或生产的记录器实施。

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.

这篇关于为什么使用singleton而不是静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆