PHP 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 '测试'; } } 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 '+': self::$obj = new OperationAdd($A,$B); break; case '-': self::$obj = new OperationSub($A,$B); break; case '*': self::$obj = new OperationMul($A,$B); break; case '/': self::$obj = new OperationDiv($A,$B); break; } return self::$obj; } } //$obj = OperationFactory::CreateOperation('+'); //$obj->setNumber(4,4); $obj = OperationFactory::CreateOperation('*',5,6); echo $obj->getResult(); /1* echo '<br>'; $obj->clearResult(); echo '<br>'; echo $obj->_Result; */
Example 3:
<?php //抽象工厂 //青铜会员的打折商品 class BronzeRebateCommodity { //描述 public $desc = '青铜会员的打折商品'; } //白银会员的打折商品 class SilverRebateCommodity { public $desc = '白银会员的打折商品'; } //青铜会员的推荐商品 class BronzeCommendatoryCommodity { public $desc = '青铜会员的推荐商品'; } //白银会员的推荐商品 class SilverCommendatoryCommodity { public $desc = '白银会员的推荐商品'; } //各个工厂的接口 interface ConcreteFactory { //生产对象的方法 public function create($what); } //青铜工厂 class BronzeFactory implements ConcreteFactory { //生产对象的方法 public function create($what){ $productName = 'Bronze'.$what.'Commodity'; return new $productName; } } //白银工厂 class SilverFactory implements ConcreteFactory { //生产对象的方法 public function create($what){ $productName = 'Silver'.$what.'Commodity'; return new $productName; } } //调度中心 class CenterFactory { //获取工厂的方法 public function getFactory($what){ $factoryName = $what.'Factory'; return new $factoryName; } //获取工厂的静态方法 public static function getFactory2($what){ $factoryName = $what.'Factory'; return new $factoryName; } } //实例化调度中心 $center = new CenterFactory(); //获得一个白银工厂 $factory = $center->getFactory('Silver'); //让白银工厂制造一个推荐商品 $product = $factory->create('Commendatory'); //得到白银会员的推荐商品 echo $product->desc.'<br>'; //获得一个青铜工厂 $factory2 = CenterFactory::getFactory2('Bronze'); //让青铜工厂制造一个打折商品 $product2 = $factory2->create('Rebate'); //得到青铜会员的推荐商品 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['extension'])){ case 'jpg': $return = new Image_JPEG($file); break; case 'png': $return = new Image_PNG($file); break; default: echo '图片类型不正确'; break; } if($return instanceof IImage){ return $return; }else{ echo '出错了'; exit(); } } } $image = ImageFactory::factory('images/11.jpg'); var_dump($image->getWidth()); echo '<br>'; print_r($image->getheight()); echo '<br>'; print_r($image->getData());
For more PHP design patterns: factory pattern related articles, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.
