简体   繁体   English

Singleton的无状态实例方法线程安全性(C#)

[英]Singleton's stateless instance method thread safety (C#)

Is it thread safe to make Converter a singleton? 使Converter成为单例线程安全吗?

public interface IConverter<TFoo, TBar>
    where TFoo : class, new()
    where TBar : class, new()
{
    TFoo ToFoo(TBar q);
    TBar ToBar(TFoo q);
}

public class Converter : IConverter<Foo, Bar>
{
    public Foo ToFoo(Bar b) {return new Foo(b);}
    public Bar ToBar(Foo f) {return new Bar(f);}
}

Yes, that's absolutely fine. 是的,那绝对很好。 There's no state, thus no thread safety issues - and there's no reason to have multiple instances. 没有状态,因此没有线程安全问题-也没有理由拥有多个实例。 It's a fairly natural singleton. 这是一个很自然的单身人士。

Of course it's nice to use the interface where you can, for flexibility and testability - but when you know you want to use that specific implementation, a singleton instance is fine. 当然,可以使用该接口很好,以提高灵活性和可测试性-但是,当您知道要使用该特定实现时,可以使用单例实例。

是的,实现不执行任何依赖状态的操作。

Yes, as the class has no data members, you can make it a singleton. 是的,由于该类没有数据成员,因此可以将其设为单例。

As the class is so small, you can just create a static instance of it: 由于类太小,您可以仅创建它的静态实例:

public class Converter : IConverter<Foo, Bar> {

  private static _instance = new Converter();

  public static Instance { get { return _instance; } }

  public Foo ToFoo(Bar b) {return new Foo(b);}
  public Bar ToBar(Foo f) {return new Bar(f);}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM