Use static class by interface?

2019-04-28 08:19发布

问题:

imagine you have some methods you need to access from your whole application. A static class is ideal for this.

public static class MyStaticClass
{
    public static void MyMethod()
    {
        // Do Something here...
    }
}

But maybe in future I'll add a second implementation of the static methods in another static class.

public static class MyStaticClass2
{
    public static void MyMethod()
    {
        // Do Something here...
    }
}

Is there a way to change static class used in my other code without changing the calls from MyStaticClass.MeMethod(); to MyStaticClass2.MyMethod();?

I thought about an interface but i have no idea how to implement this... If I'm talking crazy say it and I'll simply change the calls :D

回答1:

You want a factory pattern

so your factory is

public static MyStaticClassFactory
{
   public static IMyNonStaticClassBase GetNonStaticClass()
   {
      return new MyNonStaticClass1();    
   }

}

Instance

public class MyNonStaticClass1 : IMyNonStaticClassBase
{
    //
}

Interface

public interface IMyNonStaticClassBase
{
   void MyMethod();
}


回答2:

We use (Windsor Castle) https://www.nuget.org/packages/Castle.Windsor as factory Container.

It's the same principal.

You can have many implementations per individual Interface, but only one is ever associated to the interface in the Factory at run-time.

All you need to do is swap the implementation class at the Factory Level when you need to.

This is a really useful tool if your looking to optimize your code, i.e an Implementation class, as you have the safety of knowing that if you find any bugs in your new implementation class, you can simple swap out the implementation for the pre-existing one.