Home > Article > Backend Development > PHP factory design pattern
1. Factory pattern
is a class that has certain methods for creating objects for you. You can use a factory class to create objects without using new directly. This way, if you want to change the type of object created, you only need to change the factory. All code using this factory is automatically changed.
The following code is a sample column showing the 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 list of feedback, and get articles related to a specific feedback.
The IUser interface defines what operations the user object should perform:
interface IUser { function getName(); }
The implementation of IUser is called User:
class User implements IUser { public function __construct( $id ) { } public function getName() { return "Jack"; } }
The UserFactory factory class creates the IUser object:
class UserFactory { public static function Create( $id ) { return new User( $id ); } }
The test code will request the User
object from the factory and output the result of the getName
method:
$pr = UserFactory::Create( 1 );echo( $pr->getName()."\n" );
There is a variant of the factory pattern that uses the factory method. These public static methods in a 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 and then set a number of properties. This version of the factory pattern encapsulates the process in a single location, so you don't have to copy complex initialization code and paste it all over the code base.
interface IUser //接口{ function getName(); } class User implements IUser { public static function Load( $id ) //静态函数 { return new User( $id ); } public static function Create( ) //静态函数 { return new User( null ); } public function __construct( $id ) { }//构造函数 public function getName() { return "Jack"; } } $uo = User::Load( 1 );echo( $uo->getName()."\n" );
The above is the detailed content of PHP factory design pattern. For more information, please follow other related articles on the PHP Chinese website!