In real cases you are using the Factory pattern (method) and the benefits

Can you provide a practice for using a Factory (method) pattern ? And the benefits you have received are significant.

Thanks.

+2


a source to share


2 answers


.Net System.Data.Common.DbProviderFactory can be used to write 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 that.

+1


a source


This pattern is fairly common in OO frameworks. It is used because it provides control over the creation of objects. You can then use it for various purposes, cache your objects, use it to force merge, error checking (is the object you requested being requested?), Logging, and more whatever you want when someone instantiates a class.

As a side effect, good code does this as well. For example, in PHP, instead of

$person = new Person();
$person->setName('Mike');

      



You can do

$person = $this->load('Person')->setName('Mike');

      

+1


a source







All Articles