Home > Backend Development > PHP Tutorial > Simple practical examples of various PHP design patterns

Simple practical examples of various PHP design patterns

小云云
Release: 2023-03-21 11:18:01
Original
1625 people have browsed it

I have always felt that frameworks, versions, and even languages ​​really don’t matter to a coder. Mastering a particularly advanced framework or a new, minority language really doesn’t matter, because you It’s okay, it’s okay if I want to spend time, everyone is like this. Therefore, the basic ones are particularly important, namely algorithms and data structures, and then good design patterns.

Single case mode

Single case mode features

  • $_instance must be declared as a static private variable

  • Constructors and clone functions must be declared as private. This is to prevent external programs from adding new classes and thus losing the meaning of the singleton mode.

  • The getInstance() method must be declared as public. This method must be called to return a reference to a unique instance

  • :: The operator can only access static variables or static functions

  • Single PHP The example mode is relative, because PHP's interpretation and execution mechanism causes all related resources to be recycled after each PHP page is interpreted and executed.

<?php
header("Content-type: text/html; charset=utf-8");
    class single{
        public static $arr=array(&#39;host&#39;=>&#39;XXX&#39;,&#39;user&#39;=>&#39;XXX&#39;,&#39;password&#39;=>&#39;XXX&#39;);
        private static $_instance =null;
        private function __construct(){}
        private function __clone(){}
        static public function getInstance(){
            if(self::$_instance== null || isset(self::$_instance)){
                self::$_instance= new self;
            }
                return self::$_instance;   
        }
        public function showSomething(){
            return self::$arr;
        }
    }
    /////////////////////test///////////////
    $a=single::getInstance();
    print_r(single::getInstance()->showSomething());
?>
Copy after login

Factory pattern

The factory class is a class specially used to create other objects. The factory class is very important in the practice of polymorphic programming. It allows dynamic replacement of classes and modification of configurations, making the application more flexible. Mastering the factory pattern is essential for web development.
Features:

The factory pattern is usually used to return different classes similar to interfaces. A common use of factories is to create polymorphic providers.

Usually the factory pattern has a key construct, which is a static method generally named factory. This static method can accept any number of parameters and must return an object.

The factory pattern is further divided into:

Simple Factory Pattern

Factory Method Pattern

Abstract Factory Pattern )
Simple factory mode: used to produce any product in the same hierarchical structure. There is nothing you can do about adding new products

Factory model: used to produce fixed products in the same hierarchical structure. (Supports adding any product)

Abstract factory: used to produce all products of different product families. (There is nothing you can do about adding new products; support adding product families)

<?php
//简单工厂模式
header("Content-type: text/html; charset=utf-8");
class simpale{
    public function calculate($num1,$num2,$operator){
                try {
                    $result=0;
                    switch ($operator){
                        case &#39;+&#39;:
                            $result= $num1+$num2;
                            break;
                        case &#39;-&#39;:
                            $result= $num1-$num2;
                            break;
                        case &#39;*&#39;:
                            $result= $num1*$num2;
                            break;
                        case &#39;/&#39;:
                            if ($num2==0) {
                                throw new Exception("除数不能为0");
                            }
                            $result= $num1/$num2;
                            break;
                    }
                return $result;
                }
                catch (Exception $e){
                    echo "您输入有误:".$e->getMessage();
               }
            }
}
//工厂方法模式
    interface  people {
            function  jiehun();
    }
    //定义接口
    class man implements people{
        public $ring=null;
        public $car=null;
        public $house=null;
        public function getAllthing(){
            $this->ring=&#39;10000&#39;;
            $this->car=&#39;100000&#39;;
            $this->house=&#39;1000000&#39;;
        }
        public function jiehun() {
            if($this->ring && $this->car && $this->house)
                        echo &#39;我可以结婚了<br>&#39;;
                    else
                        echo &#39;我是臭屌丝,还不能结婚<br>&#39;;
        }
    }
    class women implements people {
        public $face=&#39;ugly&#39;;
        public function getAllthing(){
            $this->face=&#39;nice&#39;;
        }
          public function jiehun() {
                    if($this->face ==&#39;nice&#39;)
                        echo &#39;我可以结婚了<br>&#39;;
                    else
                        echo &#39;我是臭屌丝,还不能结婚<br>&#39;;
            }
    }
    interface  createpeople { 
        // 注意了,这里是工厂模式本质区别所在,将对象的创建抽象成一个接口。
          public function create();
    }
    class FactoryMan implements createpeople{
          public  function create() {
                    return  new man;
            }
    }
    class FactoryWomen implements createpeople {
           public function create() {
                    return new women;
            }
    }
    class  Client {
        // 简单工厂里的静态方法
            public function test() {
                $Factory =  new  FactoryMan;
                $man = $Factory->create();
                $man->jiehun();
                $Factory =  new  FactoryWomen;
                $woman = $Factory->create();
                $woman->getAllthing();
                $woman->jiehun();
            }
    }
/////////////test////////////
    $f = new Client;
    $f->test();
//抽象模式就是在工厂模式下接口中添加相应的不同方法即可
?>
Copy after login

Strategy Pattern

Strategy pattern is the behavior pattern of an object, intended to encapsulate a set of algorithms. Dynamically select the required algorithm and use it.
Strategy mode refers to a mode involving decision-making control in the program. The strategy pattern is very powerful because the core idea of ​​this design pattern itself is the polymorphic idea of ​​object-oriented programming.
Three characteristics of the strategy pattern:

Define the abstract role class (define the common abstract method of each implementation)

Define the specific strategy class (the common method of the specific implementation parent class)

Define environment role class (privately declare abstract role variables, overload construction methods, execute abstract methods)

<?php
abstract class baseAgent { //抽象策略类
        abstract function PrintPage();
    }
    //用于客户端是IE时调用的类(环境角色)
    class ieAgent extends baseAgent {
        function PrintPage() {
            return &#39;IE&#39;;
        }
    }
    //用于客户端不是IE时调用的类(环境角色)
    class otherAgent extends baseAgent {
        function PrintPage() {
            return &#39;not IE&#39;;
        }
    }
    class Browser {
    //具体策略角色
        public function call($object) {
            return $object->PrintPage ();
        }
    }
///////////////test////////////////
    $bro = new Browser ();
    echo $bro->call (new ieAgent );
Copy after login

Related recommendations:

Combination of PHP design patterns Pattern and case sharing

Common PHP design pattern sharing

Introduction to commonly used design patterns in PHP and their usage examples

The above is the detailed content of Simple practical examples of various PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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