Sağlıksız Dünyamız

Page 53

The Factory Pattern

Why is this bad? Connection parameters are spread all over, and while I’ve shown the parameters as constants, implying you have a way to define them centrally and globally, the solution is obviously not optimal: • While you can change the values of the parameters easily, you cannot add or change the order of parameters without changing (at least) two sections of code. • You cannot easily instantiate a new class to use another kind of database connection, say a PostgresqlConnection. • It is difficult to separately test and validate the behavior of the connection object. The code would be much improved with the use of a Factory:

class Product { function getList() { $db =& $this-> >_getConnection(); //... } function &_getConnection() { return new MysqlConnection(DB_USER, DB_PW, DB_NAME); } }

The class method _getConnection() centralizes the otherwise repetitious MysqlConnection(DB_USER, DB_PW, DB_NAME) calls found in the class’s other methods. Here’s another variation of a Factory, this one a static call to a Factory class:

new

class Product { function getList() { $db =& DbConnectionBroker::getConnection(); //... } } class DbConnectionBroker { function &getConnection() { return new MysqlConnection(DB_USER, DB_PW, DB_NAME); } }

DbConnectionBroker::getConnection() produces the same result as the previous Factory, but has a

55


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.