Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have a Create method instead of using "new"?

Tags:

c#

constructor

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.

like image 805
Michael Prewecki Avatar asked May 18 '09 03:05

Michael Prewecki


2 Answers

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.

like image 148
Yishai Avatar answered Nov 04 '22 20:11

Yishai


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....
}
like image 38
ratchetr Avatar answered Nov 04 '22 20:11

ratchetr