Unfortunately, the Singleton pattern really cannot help you here, since this template is specifically designed to return one and only one instance for the whole life of the application.
Singletones are useful for some cases, such as Logging, but they are usually avoided because they are known to be difficult to mock, test, and distribute.
If possible, I would recommend refactoring the above code using Inversion of Control Pattern and constructor dependency injection. This is achieved by creating an interface, say ILibrary , which has two implementations.
These implementations can be created once and saved to emulate behavior similar to Singleton in a third helper class. A good way to do this in a corporate application is to use a dependency injection container that supports instance lifetimes (Singleton or Transient) and makes it easy to inject into constructors.
Sample code using IoC / DI as a template will look like this:
public class A { private readonly ILibrary _library; public A(ILibrary library) { _library = library; } public DoSomething() { _library.DoStuff(); } } public class B { private readonly ILibrary _library; public B(ILibrary library) { _library = library; } public DoSomething() { _library.DoStuff(); } } public interface ILibrary { void DoStuff(); } public class LibraryTypeOne : ILibrary { void DoStuff() { Console.WriteLine("I am library type one"); } } public class LibraryTypeTwo : ILibrary { void DoStuff() { Console.WriteLine("I am library type two"); } } public static class MyProgram { var a = new A(new LibraryTypeOne());
source share