Use static class on interface?

Imagine that you have some methods needed to access from your entire application. A static class is ideal for this.

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

But perhaps in the future I will add a second implementation of static methods to another static class.

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

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

I was thinking about the interface, but I have no idea how to implement this ... If I talk crazy, say it and I just change the calls: D

+6
source share
2 answers

Do you want factory pattern

therefore your factory

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

Instance

 public class MyNonStaticClass1 : IMyNonStaticClassBase { // } 

Interface

 public interface IMyNonStaticClassBase { void MyMethod(); } 
+11
source

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

This is the same principle.

You can have many implementations on a separate interface, but only one of them is always associated with the interface in the factory at runtime.

All you have to do is change the factory implementation class when you need to.

This is a really useful tool if you want to optimize your code, that is, the implementation class, because you have security, knowing that if you find any errors in your new implementation class, you can simply replace the implementation with an existing one.

+1
source

Source: https://habr.com/ru/post/955117/


All Articles