Deprecated: Assigning the return value of new by reference is deprecated in /var/www/l3s6524/html/datensarg/wordpress/wp-settings.php on line 512 Deprecated: Assigning the return value of new by reference is deprecated in /var/www/l3s6524/html/datensarg/wordpress/wp-settings.php on line 527 Deprecated: Assigning the return value of new by reference is deprecated in /var/www/l3s6524/html/datensarg/wordpress/wp-settings.php on line 534 Deprecated: Assigning the return value of new by reference is deprecated in /var/www/l3s6524/html/datensarg/wordpress/wp-settings.php on line 570 Deprecated: Assigning the return value of new by reference is deprecated in /var/www/l3s6524/html/datensarg/wordpress/wp-includes/cache.php on line 103 Deprecated: Assigning the return value of new by reference is deprecated in /var/www/l3s6524/html/datensarg/wordpress/wp-includes/query.php on line 61 Deprecated: Assigning the return value of new by reference is deprecated in /var/www/l3s6524/html/datensarg/wordpress/wp-includes/theme.php on line 1109 Datensarg » Blog Archive » Factory Design Pattern

Factory Design Pattern

Design Patters part 1.

I built these samples on PHP design patterns a while ago to make some friends write better code. They ignored it, so I give it to you. I hope they are self-explanatory. If not: Feel free to ask!

First off: The factory design pattern. It encapsulates the creation of a class so an object can be instantiated using the factory’s create-method rather than the class’ constructor. This comes in handy if you’re planning to extend your application (usually you are) and don’t want to change every call to your class’ constructor.

//------------------------------------------------
// Factory: The "factory pattern" creates an object
// using a method rather than a constructor
//------------------------------------------------
// Definition
class MyClass
{
	public $content = "Hello world!\n";
}

class MyClassFactory
{
	public function Create()
	{
		return new MyClass();
	}
}

// Usage
$myObject= MyClassFactory::Create();
echo $myObject->content; // "Hello world!"

Leave a Reply