First, the factory model
is a class that has some methods for creating objects for you. You can use the factory class to create objects without using new directly. This way, if you want to change the type of object you are creating, you can simply change the factory. All code that uses the factory is automatically changed.
The following code shows an example of a factory class. The server side of the equation consists of two parts: a database and a set of PHP pages that allow you to add feedback, request a feedback list, and get articles related to specific feedback.
The Iuser interface defines what the user object should do:
Interface iuser{ function GetName ();}
The implementation of Iuser is called User:
Class User implements iuser{public function __construct ($id) {} public function GetName () { return "Ja CK "; }}
The Userfactory factory class creates Iuser objects:
Class userfactory{public static function Create ($id) { return new User ($id);} }
The test code requests the object to the factory User
and outputs getName
The result of the method:
$PR = userfactory::create (1); Echo ($pr->getname (). " \ n ");
There is a factory pattern variant that uses the factory method. These public static methods in the class construct objects of that type. This method is useful if it is important to create objects of this type. For example, suppose you need to create an object first, and then set many properties. This version of the factory pattern encapsulates the process in a single location, so that you don't have to copy complex initialization code or paste the copied code around the code base.
Interface Iuser//interface { function getName ();} class User implements iuser{public static function Load ($id)//static functions c4/>{ return new User ($id); } public static function Create ()//static functions { return new User (null); } Public function __construct ($id) {}//constructor public function GetName () { return "Jack"; }} $uo = User: : Load (1), Echo ($uo->getname (). " \ n ");