Reading list Switch to dark mode

    How to Use Factory Design Pattern

    Updated 9 June 2017

    Design Pattern :- Design Pattern is a way to represent your useful code and project in a well defined manner by following some standard pattern  and also used for encapsulating the large data for your project.

    Today we will focus on one of the useful and commonly used design pattern i.e Factory Design Pattern.

    Factory Design Pattern

    Basically, Factory is a way to return the object of other classes. In Factory classes we simply create the the static methods inside these methods we can create object of other class.

    In the below example, We create a file cart.php in which we used a class named Cart to get and set the information of customer and products. In cart class we used getName() and setName() functions for customer details,  getProductDetails() and setProductDetails() functioned for product details.

    Start your headless eCommerce
    now.
    Find out More
    <?php
    
    /**
     * @category Webkul
     * @package Factory Design Pattern
     * @author [Webkul] <[<http://webkul.com/>]>
     * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited
     (https://webkul.com)
     * @license https://store.webkul.com/license.html
     */
    
      /**
       * Cart Class contains Functions get, set, showCustomerDetails and showProductDetails
       * This class is used for displaying the customer and Product data
       */
        abstract class Cart
        {
          private $customer_name;
          private $product_details = array();
    
            public function getName(){
                return $this->customer_name;
            }
    
            public function setName($cust_name){
                $this->customer_name = $cust_name;
            }
    
            public function getProductDetails(){
                return $this->product_details;
            }
    
            public function setProductDetails($prod_details){
                if(!empty($prod_details)){
                    $this->product_details = $prod_details;
                }
            }
    
            public function showCustomerDetails(){
                print_r('Customer Name :- '.$this->getName().'<br>');
            }
    
            public function showProductDetails(){
                foreach ($this->getProductDetails() as $key => $product) {
                    print_r('<br>Product : '.$product['name']. ' Price : '.$product['price'].'<br>');
                }
            }
        }
     ?>
    

    We also used showCustomerDetails() and showProductDetails() functions
    to print the output of customer name and product details respectively.

    We extends the above class i.e. Cart into CartDetails Class, that is defined
    in other file named cart_details.php.

    <?php
       include 'cart.php';
    
          /**
           * @category Webkul
           * @package Factory Design Pattern
           * @author [Webkul] <[<http://webkul.com/>]>
           * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
           * @license https://store.webkul.com/license.html
           */
    
           /**
            * CartDetails to set the data for Cart class i.e. parent class
            */
          class CartDetails extends Cart
          {
              function __construct()
              {
                  parent::setName('John Doe');
                  parent::setProductDetails(array(array('name' => 'Mac Book', 'price' => '$65'),array('name' => 'samsung j7', 'price' => '$40'),array('name' => 'Canon EOS 5D', 'price' => '$15')));
              }
          }
    
          /**
           * CartFactory this is a Factory class for Cart class
           */
          class CartFactory
          {
    
              public static function createObject(){
                  /**
                   * Here we create Object of CartDetails Class i.e. new CartDetails(), Inside the createObject() of CartFactory Class
                   */
                  $cart_obj = new CartDetails();
                  CartFactory::printDetails($cart_obj);
              }
    
              public static function printDetails($cart_obj){
                  $cart_obj->showCustomerDetails();
                  $cart_obj->showProductDetails();
              }
          }
    
          // Calling Factory Class Function
          CartFactory::createObject();
     ?>
    

    In CartDetails class, we defined a non parameterized constructor and called
    setName() and setProductDetails() functions to set the customer and product
    data.

    Here we used Factory class named CartFactory Class inside cart_details.php
    In CartFactory class we used two static methods named : createObject() and
    printDetails()

    If you will see in above CartFactory class, we create an object of CartDetails
    class like:

    public static function createObject(){
        /**
          * Here we create Object of CartDetails Class i.e. new CartDetails(), Inside the createObject() of CartFactory Class
          */
          $cart_obj = new CartDetails();
          CartFactory::printDetails($cart_obj);
    
    }

    and by using this object, called the printDetails($cart_obj) function of CartFactory class. Now with the help of $cart_obj object you can call functions of CartDetails and Cart classes.

    Like:-

    public static function printDetails($cart_obj){
         $cart_obj->showCustomerDetails();
         $cart_obj->showProductDetails();
    }
    
    Output:-
    
       Customer Name :- John Doe
       Product : Mac Book Price : $65
       Product : samsung j7 Price : $40
       Product : Canon EOS 5D Price : $15

    Benefits of using Factory Design Pattern:-

    1) By using Factory Design Pattern like in above example if you want to change
    some code in Cart and CartDesigns classes, then you have to change code only
    in Factory class, instead of in complete project where you used Cart and CartDesigns
    classes.

    2) By using Factory classes you can encapsulate your code/data.

    3) You can also reduce the code repetition while creating the object of
    other classes.

    Thanks 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home