Sunday 26 June 2016

Factory Design Pattern

The factory method as the name suggests  is a method/process whose main purpose in life is to create objects. Most commonly (and really per definition) the factory method is an interface method that delegates object instantiation decisions to sub classes. It works on the principle of " separation of concerns ". 
Advantage of Factory Pattern - Loose Coupling and Segregation of Responsibilities. Now instead of hard binding the complete logic to decide the nature and shape of the object on the basis of some conditions, you are assigning the responsibility to some other object and hence making the relationship loosely coupled and hence maintainable.In the following example, the Company class's only job is to create objects of other classes, there by giving the responsibility to other classes to implement the respective functionality.

<?php
Class Company {
public function getEmpDetails() {
new Employee();
}
public function getSalesInfo() {
new Sales();
}
public function getProductsInfo() {
new Products();
}
}
Class Employee {
public function __construct() {
echo "Employee Details are : ";
}
}
Class Sales {
public function __construct() {
echo "Sales Info : ";
}
}
Class Products {
public function __construct() {
echo "Products Info : ";
}
}
$company = new Company();
$company->getEmpDetails();
$company->getSalesInfo();
$company->getProductsInfo();
?>

No comments:

Post a Comment