search
HomeBackend DevelopmentPHP TutorialPHP design pattern: factory pattern

Factory pattern:

The factory class determines which instance of the product class to create based on the parameters;

The factory class refers to a class that contains a method specifically used to create other objects. The so-called on-demand allocation is to pass in parameters for selection and return a specific class. The main function of the factory pattern is to encapsulate object creation and simplify object creation operations.

Simply put, it is to call a method of the factory class (pass in parameters) to get the required class;

Code implementation:

Example 1 (the most basic factory class):

<?php
 
class MyObject {
 
public function __construct(){}
 
public function test(){
return &#39;测试&#39;;
}
 
}
 
class MyFactory {
 
public static function factory(){
//返回对象的实例
return new MyObject();
}
 
}
 
//调用工厂类MyFactory中的静态方法,获取类MyObject的实例
$myobject=MyFactory::factory();
echo $myobject->test();

Example 2:

<?php
//简单工厂模式
/1*
 * 定义运算类
 */
abstract class Operation {
 
protected $_NumberA = 0;
protected $_NumberB = 0;
protected $_Result  = 0;
 
public function __construct($A,$B){
$this->_NumberA = $A;
$this->_NumberB = $B;
}
 
public function setNumber($A,$B){
$this->_NumberA = $A;
$this->_NumberB = $B;
}
 
/1*
protected function clearResult(){
$this->_Result  = 0;
}
*/
 
public function clearResult(){
$this->_Result  = 0;
}
 
//抽象方法无方法体
abstract protected function getResult();
 
}
 
//继承一个抽象类的时候,子类必须实现抽象类中的所有抽象方法;
//另外,这些方法的可见性 必须和抽象类中一样(或者更为宽松)
class OperationAdd extends Operation {
 
public function getResult(){
$this->_Result=$this->_NumberA + $this->_NumberB;
return $this->_Result;
}
 
}
 
class OperationSub extends Operation {
 
public function getResult(){
$this->_Result=$this->_NumberA - $this->_NumberB;
return $this->_Result;
}
 
}
 
class OperationMul extends Operation {
 
public function getResult(){
$this->_Result=$this->_NumberA * $this->_NumberB;
return $this->_Result;
}
 
}
 
class OperationDiv extends Operation {
 
public function getResult(){
$this->_Result=$this->_NumberA / $this->_NumberB;
return $this->_Result;
}
 
}
 
class OperationFactory {
 
//创建保存实例的静态成员变量
private static $obj;
 
//创建访问实例的公共的静态方法
public static function CreateOperation($type,$A,$B){
switch($type){
case &#39;+&#39;:
self::$obj = new OperationAdd($A,$B);
break;
case &#39;-&#39;:
self::$obj = new OperationSub($A,$B);
break;
case &#39;*&#39;:
self::$obj = new OperationMul($A,$B);
break;
case &#39;/&#39;:
self::$obj = new OperationDiv($A,$B);
break;
}
return self::$obj;
}
 
}
 
//$obj = OperationFactory::CreateOperation(&#39;+&#39;);
//$obj->setNumber(4,4);
$obj = OperationFactory::CreateOperation(&#39;*&#39;,5,6);
echo $obj->getResult();
/1*
echo &#39;<br>&#39;;
$obj->clearResult();
echo &#39;<br>&#39;;
echo $obj->_Result;
*/

Example 3:

<?php
//抽象工厂
 
//青铜会员的打折商品
class BronzeRebateCommodity {
//描述
public $desc = &#39;青铜会员的打折商品&#39;;
}
 
//白银会员的打折商品
class SilverRebateCommodity {
public $desc = &#39;白银会员的打折商品&#39;;
}
 
//青铜会员的推荐商品
class BronzeCommendatoryCommodity {
public $desc = &#39;青铜会员的推荐商品&#39;;
}
 
//白银会员的推荐商品
class SilverCommendatoryCommodity {
public $desc = &#39;白银会员的推荐商品&#39;;
}
 
//各个工厂的接口
interface ConcreteFactory {
//生产对象的方法
public function create($what);
}
 
//青铜工厂
class BronzeFactory implements ConcreteFactory {
 
//生产对象的方法
public function create($what){
$productName = &#39;Bronze&#39;.$what.&#39;Commodity&#39;;
return new $productName;
}
 
}
 
//白银工厂
class SilverFactory implements ConcreteFactory {
 
//生产对象的方法
public function create($what){
$productName = &#39;Silver&#39;.$what.&#39;Commodity&#39;;
return new $productName;
}
 
}
 
//调度中心
class CenterFactory {
 
//获取工厂的方法
public function getFactory($what){
$factoryName = $what.&#39;Factory&#39;;
return new $factoryName;
}
 
//获取工厂的静态方法
public static function getFactory2($what){
$factoryName = $what.&#39;Factory&#39;;
return new $factoryName;
}
 
}
 
//实例化调度中心
$center  = new CenterFactory();
//获得一个白银工厂
$factory = $center->getFactory(&#39;Silver&#39;);
//让白银工厂制造一个推荐商品
$product = $factory->create(&#39;Commendatory&#39;);
//得到白银会员的推荐商品
echo $product->desc.&#39;<br>&#39;;
 
//获得一个青铜工厂
$factory2 = CenterFactory::getFactory2(&#39;Bronze&#39;);
//让青铜工厂制造一个打折商品
$product2 = $factory2->create(&#39;Rebate&#39;);
//得到青铜会员的推荐商品
echo $product2->desc;

Example 4:

<?php
//使用工厂类解析图像文件
interface IImage {
 
function getWidth();
function getHeight();
function getData();
 
}
 
class Image_PNG implements IImage {
 
protected $_width,$_height,$_data;
 
public function __construct($file){
$this->_file = $file;
$this->_parse();
}
 
private function _parse(){
//完成PNG格式的解析工作
//并填充$_width,$_height和$_data
$this->_data   = getimagesize($this->_file);
list($this->_width,$this->_height)=$this->_data;
}
 
public function getWidth(){
return $this->_width;
}
 
public function getHeight(){
return $this->_height;
}
 
public function getData(){
return $this->_data;
}
 
}
 
class Image_JPEG implements IImage {
 
protected $_width,$_height,$_data;
 
public function __construct($file){
$this->_file = $file;
$this->_parse();
}
 
private function _parse(){
//完成JPEG格式的解析工作
//并填充$_width,$_height和$_data
//$this->_width  = imagesx($this->_file);
//$this->_height = imagesy($this->_file);
$this->_data   = getimagesize($this->_file);
list($this->_width,$this->_height)=$this->_data;
}
 
public function getWidth(){
return $this->_width;
}
 
public function getHeight(){
return $this->_height;
}
 
public function getData(){
return $this->_data;
}
 
}
 
//工厂类
class ImageFactory {
 
public static function factory($file){
 
$filename = pathinfo($file);
switch(strtolower($filename[&#39;extension&#39;])){
case &#39;jpg&#39;:
$return = new Image_JPEG($file);
break;
case &#39;png&#39;:
$return = new Image_PNG($file);
break;
default:
echo &#39;图片类型不正确&#39;;
break;
}
if($return instanceof IImage){
return $return;
}else{
echo &#39;出错了&#39;;
exit();
}
 
}
 
}
 
$image = ImageFactory::factory(&#39;images/11.jpg&#39;);
var_dump($image->getWidth());
echo &#39;<br>&#39;;
print_r($image->getheight());
echo &#39;<br>&#39;;
print_r($image->getData());



For more PHP design patterns: factory pattern related articles, please pay attention to the PHP Chinese website!

Statement
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment