Let's say I have a family of maths algorithms that all should follow same structures, so I wanted each of these classe开发者_开发问答s to implement a common interface class. But the compiler says it's not possible for static class.
So what should I do:
- Make static non static
- Or use Inheritance
- Or better alternative?
I would recommend you using an interface or an abstract base class along with a factory which will return the proper algorithm implementation based on some input. By making those classes implement an interface you will also bring weaker coupling between the consumers of those methods and the algorithms and you will also benefit from the possibility of unit testing in isolation the different parts of your application.
UPDATE:
Here's an example using an interface:
public interface IMathAlgorithm
{
double Add(double a, double b);
}
public class FooAlgorithm : IMathAlgorithm
{
public double Add(double a, double b)
{
return StaticFoo.Add(a, b);
}
}
public class BarAlgorithm : IMathAlgorithm
{
public double Add(double a, double b)
{
return StaticBar.Add(a, b);
}
}
Now the consumers will always work with the IMathAlgorithm
interface because all they care about is adding two numbers and not the way this adding is implemented. The factory pattern could ease the creation of a specific implementation of a given algorithm but DI frameworks do this job just fine.
Now if you have some ugly legacy code that you don't have control over and which depends on static classes/methods you could invoke it in the specific implementation of a given algorithm. The advantage is that it is now hidden behind the specific implementation and the consumers of the algorithm don't have to call/rely on it explicitly.
Just make your class non-static and implement your interface. Factory is about encapsulating your concrete class inside the factory and provide only the instance of the interface to the outside, which appropriates for your situation but not mandatory.
精彩评论