What are the advantages and when is it appropriate to use a static constructor?
public class MyClass
{
protected MyClass()
{
}
public static MyClass Create()
{
return new MyClass();
}
}
and then creating an instance of the class via
MyClass myClass = MyClass.Create();
as opposed to just having a public constructor and creating objects using
MyClass myClass = new MyClass();
I can see the first approach is useful if the Create method returns an instance of an interface that the class implements...it would force callers create instances of the interface rather than the specific type.
This is the factory pattern, and it could often be used to produce a subclass, but allow the parameters to the static method determine which one.
It could also be used if a new object isn't always required, for example in a pooling implementation.
It can also be used if all instances of the object needs to be cached or otherwise registered upon creation. This ensures that the client doesn't forget to do that.
And of course, it is part and parcel of the Singleton pattern.
This is not a singleton...Create would return the same instance every time if it was.
This is a factory pattern. I would normally do this with interfaces not classes, so I have to stretch here, but a contrived example would be:
public static MyClass Create()
{
if(OS == Windows)
return new MyDerivedClassForWindows();
else if(OS == Linux)
return new MyDerivedClassForLinux();
etc....
}
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