Detailed explanation of common factory design patterns in PHP

黄舟
Release: 2023-03-15 14:22:02
Original
1249 people have browsed it

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();
}
Copy after login

The implementation of IUser is called User:


class User implements IUser
{  public function __construct( $id ) { } 
  public function getName()
  {    return "Jack";
  }
}
Copy after login

The UserFactory factory class creates an IUser object:


class UserFactory
{  public static function Create( $id )
  {    return new User( $id );
  }
}
Copy after login

The test code will request the User object from the factory and output getName The result of the method:


$pr = UserFactory::Create( 1 );echo( $pr->getName()."\n" );
Copy after login

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" );
Copy after login

The above is the detailed content of Detailed explanation of common factory design patterns in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!