开发者

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

Is it thread safe to make Converter a singleton?

public interface IConverter<TFoo, TBar>
    where TFoo : class, new()
    where TBar : class, new()
{
    TFoo ToFoo(TBar q);
    开发者_如何学PythonTBar 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, the implementation does nothing that depend on state.


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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜