PHP中的设计模式
抽象工厂模式
对于那些不必须要的子类模式,合并起来,通过一个类中多个方法就可以完成工厂输出
abstract class messageFactor{ abstract function getHeader(); abstract function getMail(); abstract function getMobile(); abstract function getFooter();}class smudgeMo extends messageFactor{ public function getHeader() { return 'Header'; } public function getMail() { return new Mail(); } public function getMobile() { return new Mobile(); } public function getFooter() { return 'Footer'; }}class julylovinMo extends messageFactor{// 和上个子类相似}
虽然减少了子类继承,但是耦合问题太严重,如果增加一个产品类型, 抽象函数和子类继承体,都需要增加对应的方法
abstract class factory{ const APPT = 1; const TTD = 1; const CONTACT = 1; abstract function make($flag_int);}class mailModel extends factory{ public function make($flag_int) { switch ($flag_int){ case self::APPT: return new apptEncoder(); break; case self::TTD: return new ttdEncoder(); break; case self::CONTACT: return new contactEncoder(); break; } }}
紧凑型工厂模式,但是耦合度高,不利于维护
单例模式
全局变量将类捆绑于特定环境中,破坏了封装
特点:
preference 可以被任何对象调用,无需将对象作为参数传递
preference 不该保存在全局变量中
系统中不应超过一个preference对象,即只允许实例化一次
class Preference { static $instance; public $name; private function __construct() { } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public static function getInstance() { if (empty(self::$instance)) // 控制了只有一个Preference实例对象 { self::$instance = new Preference(); } return self::$instance; }}$prf = Preference::getInstance(); // 任何地方可以获取Preference实例对象$prf->setName('Julylovin');echo $prf->getName(); // Julylovin
原型模式
用组合代替继承,抽象工厂模式有平行层次继承,会有耦合问题
使用clone关键词复制已经存在的产品, 具体产品本身,便成为自身生成的基础
class sea {private $navigability = 0 ; //可航行public function __construct($navigability) { $this->navigability = $navigability; }}class earthsea extends sea{}class plain{}class earthplain extends plain{}class forest{}class earthforest extends forest{}class factory{ private $sea; private $plain; private $forest; public function __construct(sea $sea, plain $plain, forest $forest) { $this->sea = $sea; $this->plain = $plain; $this->forest = $forest; } public function getSea() { return clone $this->sea;// 只是引用对象,是同一个对象,并非两个对象 } public function getPlain() { return clone $this->plain; } public function getForest() { return clone $this->forest; }}$earthInstance = new factory(new earthsea(1), new earthplain(), new earthforest()); //海域可航行$earthInstance->getForest(); // new earthforest() 的实例
组合模式
组合模式有助于集合和组件之间关系建立模型
枪手(Archer)组合成军队(Arm),多个枪手可以增加军队的战斗力(bombardStrength)
abstract class unit { public function addunit(Unit $unit){ // 阻止独立单元再次添加对象 throw new unitException(get_class($unit).'is a leaf'); } public function removeunit(Unit $unit){ // 阻止独立单元删除添加对象 throw new unitException(get_class($unit).'is a leaf'); } abstract function bombardStrength();}class unitException extends Exception{}class Archer extends unit { public function bombardStrength() { return 4 ; }}class Army extends unit{ //组合模式体 private $units = array(); public function addunit(Unit $unit) { if(in_array($unit, $this->units, true)) { return ; } $this->units[] = $unit; } public function removeunit(Unit $unit) { $units = array(); foreach ($this->units as $item) { if($item !== $unit) { $units[] = $item; } } $this->units = $units; } public function bombardStrength() { $ret = 0 ; foreach ($this->units as $unit) { $ret += $unit->bombardStrength(); } return $ret; }}$SubArmy = new Army();$SubArmy->addunit( new Archer());$SubArmy->addunit( new Archer());echo $SubArmy->bombardStrength(); // 8

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

AI Hentai Generator
Generate AI Hentai for free.

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



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...
