Hi folks:
Can you provide practices about leveraging Factory (method) pattern? And the benefit you got greatly.
Thanks.
Hi folks:
Can you provide practices about leveraging Factory (method) pattern? And the benefit you got greatly.
Thanks.
.Net System.Data.Common.DbProviderFactory class can be used for writing a DB-independent code.
var factory = DbProviderFactories.GetFactory(/* here you put provider name, e.g. taken from config */);
using (var connection = factory.CreateConnection())
using (var command = connection.CreateCommand())
{
connection.ConnectionString = /* some connection string, e.g. from config */;
command.CommandText = /* some query */;
command.ExecuteNonQuery();
}
Something like this.
This pattern is quite prevalent in OO frameworks. It's used because it gives the framework control over the creation of objects. You can then use it for a variety of things, caching your objects, using it to force singletons, error-checking (does the object you requested exist?), logging and pretty much anything else you want to happen when someone instantiates a class.
As a side-effect it also makes for nice code. For example in PHP instead of
$person = new Person();
$person->setName('Mike');
you can do
$person = $this->load('Person')->setName('Mike');