Table of Contents
Single case mode
Home Backend Development PHP Tutorial Simple practical examples of various PHP design patterns

Simple practical examples of various PHP design patterns

Mar 14, 2018 am 10:47 AM
php Example Design Patterns

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!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles