1、模式定义
中介者模式(Mediator)就是用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
对于中介对象而言,所有相互交互的对象,都视为同事类,中介对象就是用来维护各个同事对象之间的关系,所有的同事类都只和中介对象交互,也就是说,中介对象是需要知道所有的同事对象的。当一个同事对象自身发生变化时,它是不知道会对其他同事对象产生什么影响,它只需要通知中介对象,“我发生变化了”,中介对象会去和其他同事对象进行交互的。这样一来,同事对象之间的依赖就没有了。有了中介者之后,所有的交互都封装在了中介对象里面,各个对象只需要关心自己能做什么就行,不需要再关心做了之后会对其他对象产生什么影响,也就是无需再维护这些关系了。
2、UML类图
3、示例代码
MediatorInterface.php
<?phpnamespace DesignPatterns\Behavioral\Mediator;/** * MediatorInterface是一个中介者契约 * 该接口不是强制的,但是使用它更加符合里氏替换原则 */interface MediatorInterface{ /** * 发送响应 * * @param string $content */ public function sendResponse($content); /** * 发起请求 */ public function makeRequest(); /** * 查询数据库 */ public function queryDb();}
Mediator.php
<?phpnamespace DesignPatterns\Behavioral\Mediator;use DesignPatterns\Behavioral\Mediator\Subsystem;/** * Mediator是中介者模式的具体实现类 * In this example, I have made a "Hello World" with the Mediator Pattern. */class Mediator implements MediatorInterface{ /** * @var Subsystem\Server */ protected $server; /** * @var Subsystem\Database */ protected $database; /** * @var Subsystem\Client */ protected $client; /** * @param Subsystem\Database $db * @param Subsystem\Client $cl * @param Subsystem\Server $srv */ public function setColleague(Subsystem\Database $db, Subsystem\Client $cl, Subsystem\Server $srv) { $this->database = $db; $this->server = $srv; $this->client = $cl; } /** * 发起请求 */ public function makeRequest() { $this->server->process(); } /** * 查询数据库 * @return mixed */ public function queryDb() { return $this->database->getData(); } /** * 发送响应 * * @param string $content */ public function sendResponse($content) { $this->client->output($content); }}
Colleague.php
<?phpnamespace DesignPatterns\Behavioral\Mediator;/** * Colleague是一个抽象的同事类,但是它只知道中介者Mediator,而不知道其他同事 */abstract class Colleague{ /** * this ensures no change in subclasses * * @var MediatorInterface */ private $mediator; /** * @param MediatorInterface $medium */ public function __construct(MediatorInterface $medium) { $this->mediator = $medium; } // for subclasses protected function getMediator() { return $this->mediator; }}
Subsystem/Client.php
<?phpnamespace DesignPatterns\Behavioral\Mediator\Subsystem;use DesignPatterns\Behavioral\Mediator\Colleague;/** * Client是发起请求&获取响应的客户端 */class Client extends Colleague{ /** * request */ public function request() { $this->getMediator()->makeRequest(); } /** * output content * * @param string $content */ public function output($content) { echo $content; }}
Subsystem/Database.php
<?phpnamespace DesignPatterns\Behavioral\Mediator\Subsystem;use DesignPatterns\Behavioral\Mediator\Colleague;/** * Database提供数据库服务 */class Database extends Colleague{ /** * @return string */ public function getData() { return "World"; }}
Subsystem/Server.php
<?phpnamespace DesignPatterns\Behavioral\Mediator\Subsystem;use DesignPatterns\Behavioral\Mediator\Colleague;/** * Server用于发送响应 */class Server extends Colleague{ /** * process on server */ public function process() { $data = $this->getMediator()->queryDb(); $this->getMediator()->sendResponse("Hello $data"); }}
4、测试代码
Tests/MediatorTest.php
<?phpnamespace DesignPatterns\Tests\Mediator\Tests;use DesignPatterns\Behavioral\Mediator\Mediator;use DesignPatterns\Behavioral\Mediator\Subsystem\Database;use DesignPatterns\Behavioral\Mediator\Subsystem\Client;use DesignPatterns\Behavioral\Mediator\Subsystem\Server;/** * MediatorTest tests hello world */class MediatorTest extends \PHPUnit_Framework_TestCase{ protected $client; protected function setUp() { $media = new Mediator(); $this->client = new Client($media); $media->setColleague(new Database($media), $this->client, new Server($media)); } public function testOutputHelloWorld() { // 测试是否输出 Hello World : $this->expectOutputString('Hello World'); // 正如你所看到的, Client, Server 和 Database 是完全解耦的 $this->client->request(); }}
5、总结
中介者主要是通过中介对象来封装对象之间的关系,使之各个对象在不需要知道其他对象的具体信息情况下通过中介者对象来与之通信。同时通过引用中介者对象来减少系统对象之间关系,提高了对象的可复用和系统的可扩展性。但是就是因为中介者对象封装了对象之间的关联关系,导致中介者对象变得比较庞大,所承担的责任也比较多。它需要知道每个对象和他们之间的交互细节,如果它出问题,将会导致整个系统都会出问题。

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment