Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this how the Factory Pattern works?

The Singleton and the Registry patterns were very simple and easy for me to understand right away but the Factory pattern has been something I haven't been able to get my brain to interpret 100% yet. I think I might understand it now, I have wrote a sample code below, please review and tell me if this is the proper use of the Factory pattern. Sample is in PHP...

<?php
 /**
 *   Factory.class.php
 */
class Factory {
    public static $_database;
    public static $_cache;
    public static $_session;

    // Build our User object with all it's dependencies  
    public static function makeUserObject()
    {
        $user = new User();
        $user->setDatabaseObject(self::$_database);
        $user->setCacheObject(self::$_cache);
        $user->setSessionObject(self::$_session);
        return $user;
    }

    // other objects will be here someday......
}

/**
 *  User.class.php
 */
class User
{
    public function __construct() { }

    // inject Database Object
    public function setDatabaseObject($databaseConnectionObject)
    {
        $this->_databaseObject = $databaseConnectionObject;
    }

    // inject Cache Object
    public function setCacheObject($cacheObject)
    {
        $this->_cacheObject = $cacheObject;
    }

    // inject Session Object
    public function setSessionObject($sessionObject)
    {
        $this->_sessionObject = $sessionObject;
    }

    // other methods here for User object...........
}

/**
 *  index.php  Main page that puts it all together
 *  assume that classes are autoloaded into this page already
 */
// Set our Database + Cache + Session objects into the Factory Object
Factory::$_database = new Databse();
Factory::$_cache = new Cache();
Factory::$_session = new Session();

// Create our User object
// The factory class will build the User object and inject all
// it's dependencies for us =)
$user = Factory::makeUserObject();

?>

So basicly the Database, Cache, and Session objects are created (not shown here) then they are added to the Factory object, I the can build a method in the factory class for each object that will need any of these 3 dependencies and I can set which ones they get too. This also makes it where the individual classes can still be somewhat portable as I can directly inject there dependencies if I wanted to without the factory object. Does this sound right? If this is right, this sounds really useful


UPDATE # 1

This is based off this here a blog post I read here http://www.potstuck.com/2009/01/08/php-dependency-injection/ they refer to it as a "factory", I been using a Registry and a lot of people keep telling me to look into a "factory" and everything I read about it just didn't click in my head until I read this artcle but looks like it isn't a "factory"?


UPDATE # 2
From wikipedia http://en.wikipedia.org/wiki/Factory_object In object-oriented computer programming, a factory object is an object for creating other objects. It is an abstraction of a constructor, and can be used to implement various allocation schemes, such as the singleton pattern. A factory object typically has a method for every kind of object it is capable of creating. These methods optionally accept parameters defining how the object is created, and then return the created object. Factory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object. The factory object might decide to create the object's class (if applicable) dynamically, return it from an object pool, do complex configuration on the object, or other things.

So maybe this is a "Factory Object" in a way afterall...

like image 498
JasonDavis Avatar asked Jan 26 '10 09:01

JasonDavis


People also ask

Is the Factory pattern useful if so how?

Factory Design Pattern Advantages Factory pattern removes the instantiation of actual implementation classes from client code. Factory pattern makes our code more robust, less coupled and easy to extend. For example, we can easily change PC class implementation because client program is unaware of this.

What is the intention of the factory design pattern?

The intent of this pattern, according to Design Patterns by Gamma et al, is to: Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method allows a class to defer instantiation to subclasses.

What are the types of factory pattern?

the abstract factory pattern,the static factory method, the simple factory (also called factory).

What is factory pattern Mcq?

Factory pattern refers to newly created object using a common interface.


1 Answers

Summarized and extended my comments from below the question here

Like others said, it is not a Factory, simply because a pattern with this name does not exist. It's either an AbstractFactory or a FactoryMethod, though pragmatically people often refer to either or by just saying Factory and that's fine with me.

Session, Cache and DB are usually something you will initialize early in your application flow, so this is basically bootstrap work. I get the impression what you are looking for is not so much the creation of objects, but their handling throughout the application. That's a somewhat different concern from what a FactoryWhatever does.

Like I said in the comments, just because it isnt exactly a FactoryWhatever, doesn't mean that your code is bad. If it solves your problem, it's cool. But I still think, what you are trying to do, e.g. creating and managing resources at runtime is best used with a DI Service Container.

If you don't want to use a DI Container now for this, you could have a look at Zend_Application and how they bootstrap resources. It's an alternative and leaves the possibility to add DI containers later.

In fact, quite a lot of the topics in your previous questions have been solved in Zend Framework already, e.g. Config classes. I am not saying use ZF, but you could check it out to see how they do things. Of course, you can look at the other frameworks too.

Some pattern sites with PHP examples:

  • http://sourcemaking.com/creational_patterns
  • http://www.fluffycat.com/PHP-Design-Patterns/
  • http://www.ibm.com/developerworks/library/os-php-designptrns/?S_TACT=105AGX44&S_CMP=ART
  • http://www.ibm.com/developerworks/opensource/library/os-php-designpatterns/index.html?ca=drs-tp1308
like image 126
Gordon Avatar answered Oct 21 '22 08:10

Gordon