I wouldn't call what you used a static factory. In my eyes it's a "named constructor" since it resides in the class itself and just creates an object of that particular class.
It is often used to make the operation easier to understand, e.g. compare
int value = Int32.Parse(someString);
int value = new Int32(someString); // doesn't really exist
The first version makes it clear that it parses the input string, the second is far less verbose.
Update: one important difference between constructors and static methods like Int32.Parse
is that static methods can chose whether to return null
in case an error occured or throw an exception. A constructor can only throw an exception or - and I wouldn't recommend that - leave the object in some sort of limbo state where it is only half-initialized.
A static factory is used to decouple classes, and to make it easier to change the implementation, for example instead of instantiating a database connection using the new
operator in your code every time you need a database connection you use a factory method that returns an interface:
SqlConnection myConnection = new SqlConnection(connectionString);
IDbConnection myConnection = myFactory.CreateConnection();
The advantage is that by simply changing the CreateConnection
method you can make global changes to your entire project, swapping databases servers or even database providers without having to change your code in all the places where you actually use the database connection.