Alex Rivera | Logout

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

Asked 2009-05-18T03:10:26.313
12

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.

Edit
Report

1 Answer

2

Might be useful in cases where multiple class instances share the same block of initialized data -- this is the OOP factory pattern.

An example would be a class which connects to a database -- only one connection is required, and can be shared by all instances of the class.

http://en.wikipedia.org/wiki/Factory_pattern

Billy3

answered 2009-05-18T03:17:36.297

Your Answer