Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use static class by interface?

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

like image 586
Kai Frische Avatar asked Oct 02 '13 16:10

Kai Frische


2 Answers

You want a factory pattern

so your factory is

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

Instance

public class MyNonStaticClass1 : IMyNonStaticClassBase
{
    //
}

Interface

public interface IMyNonStaticClassBase
{
   void MyMethod();
}
like image 157
Liam Avatar answered Oct 07 '22 01:10

Liam


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.

like image 42
Derek Avatar answered Oct 07 '22 02:10

Derek