There is no such thing as a derived static method. Thus, there is no way to create a static factory method that returns a different type, depending on which derived class you are calling.
As suggested by Lonli-Lokli, you should use the factory design pattern .
public interface ISomething { void DoSomething(); } public class SomeClass : ISomething { public virtual void DoSomething() { Console.WriteLine("SomeClass"); } } public class SomeDerivedClass : SomeClass { private int parameter; public SomeDerivedClass(int parameter) { this.parameter = parameter; } public virtual void DoSomething() { Console.WriteLine("SomeDerivedClass - {0}", parameter); base.DoSomething(); } } public interface IFactory { public ISomething Create(); } public class SomeClassFactory : IFactory { public ISomething Create() { return new SomeClass(); } } public class SomeDerivedClassFactory : IFactory { public ISomething Create() { return new SomeDerivedClass(SomeParam); } public int SomeParam { get; set; } }
Advantages of abstract factory vs static factory methods :
- This is much more flexible, allowing a new implementation of your factory logic (which can be as complex as you want) for each abstract factory developer. If you want, you can have more than one factory for each class.
- Since you are not calling a static method, it is much easier to replace it at run time. This is very useful for injecting layouts in unit tests.
The pros are huge. Abstract factories are superior in all respects to static factory methods, even if you can make static methods work the way you want.
Against abstract factory vs static factory methods :
- Users of an abstract factory must have a factory instance to create your derived types.
- You need to write a new abstract factory implementation for each derived class.
The ends are very slight.
It is very simple for the user to create a factory instance to create one object:
MyClass myClass = new MyClassFactory().Create();
As for code duplication in the factory implementation: saving the implementer a tiny bit of input is pointless. The purpose of programming is to write code that can be read, understood and easily modified. There is no programming purpose for saving paper or keystrokes :)
source share