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
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With