DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

For the Nth Time, the Factory Method: A Simpler Introduction

Jose Asuncion user avatar by
Jose Asuncion
·
Mar. 22, 13 · Interview
Like (0)
Save
Tweet
Share
5.65K Views

Join the DZone community and get the full member experience.

Join For Free
I don’t know what it is, but it took me a long time to finally wrap my head around the Factory Method.

I always found the tutorials at Google not very helpful. My number one source of information wikipedia featured a very simple example that didn’t seem to drive home the point. Here it is for reference:

class Complex {
     public static Complex fromCartesian(double real, double imaginary) {
         return new Complex(real, imaginary);
     }
 
     public static Complex fromPolar(double modulus, double angle) {
         return new Complex(modulus * cos(angle), modulus * sin(angle));
     }
 
     private Complex(double a, double b) {
         //...
     }
}

The first thing that came to my mind when I saw it was that, what’s stopping me from just instantiating the above like so:

Complex number = new Complex(real, imaginary);

I know for one thing that it was a creational pattern but I never found an opportunity to use or apply it. That day has finally come though.

So when can you use it?

One of the things that spurred me to look back time again at the Factory Method was when I was trying to find a solution to the long lines of code I used creating mock objects for my unit tests. They were so long that they irritated me. I knew something was wrong, I was violating the Single Responsibility Principle.

The solution is to delegate creating the object that was going to be tested, injecting dependencies etc somewhere else. Factory methods let you do that.

An Example

Here’s an example of code where I used a factory method:

public function findByProjectId($pID)
{
   $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini');
   $config = $config->current()->toArray();
             
   $db = new PDO(
      $config['db']['connection'],
      $config['db']['username'],
      $config['db']['password']
   );
   $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
 
    $q = $db->prepare('query here');
    $q->execute(
      array(
         // params here
      )
    );      
    return $q->fetch(PDO::FETCH_ASSOC);
}

Lines 3-11 are just repetitive code that you can say are repeated in each DAO method. Instead of doing that, a better solution would be to just delegate these lines somewhere else. That somewhere else is a factory method. Here’s my implementation:

class Dao_Manager
{
   private static $DBH;
     
   public static function getPDO()
   {
      if (is_null(self::$DBH)) {
         $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini');
     $config = $config->current()->toArray();
             
    $DBH = new PDO(
       $config['db']['connection'],
       $config['db']['username'],
       $config['db']['password']
    );
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
 
    self::$DBH = $DBH;
     }
         
     return self::$DBH;
   }
}

Now we can do away with 8 lines of code and just do this instead:

public function findByProjectId($pID)
{
    $db = Dao_Manager::getPDO();
    $q = $db->prepare('query here');
    $q->execute(
      array(
         // params here
      )
    );      
    return $q->fetch(PDO::FETCH_ASSOC);
}

Now that’s a beauty.



Factory (object-oriented programming)

Published at DZone with permission of Jose Asuncion, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Exploring the Benefits of Cloud Computing: From IaaS, PaaS, SaaS to Google Cloud, AWS, and Microsoft
  • Public Cloud-to-Cloud Repatriation Trend
  • Unleashing the Power of JavaScript Modules: A Beginner’s Guide
  • Using QuestDB to Collect Infrastructure Metrics

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: