Skip to content

Instantly share code, notes, and snippets.

@jaykz52
Created December 14, 2010 03:10
Show Gist options
  • Save jaykz52/739957 to your computer and use it in GitHub Desktop.
Save jaykz52/739957 to your computer and use it in GitHub Desktop.
An example of using static factory methods in place of constructors
public class DBConnection
{
private const int MAXCONNECTIONS = 5;
private static int connectionsOpen = 0;
private DBConnection(){}
// static factory in some sort of pooling situation
public static DBConnection GetConnection()
{
while (connectionsOpen >= MAXCONNECTIONS)
// spin
// now that we've got a connection available, let's up the counter and return it
connectionsOpen++;
return new DBConnection();
}
public static DBConnection DBConnectionWithConnectionString(string pConnectionString)
{
// we'd return a new DBConnection object based on the connection string passed in
}
// NOTE: if this and the above were constructors, we'd get a compiler error b/c of the matching signatures!
public static DBConnection DBConnectionByName(string pName)
{
// maybe we have specific named instances? I don't know, but this method is more descriptive than using a constructor
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment