search
HomeBackend DevelopmentPHP TutorialPHP Design Patterns: Mediator Pattern_PHP Tutorial

PHP Design Patterns: Mediator Pattern_PHP Tutorial

Jul 13, 2016 pm 05:44 PM
phpintroducerightencapsulationusyesmodelofPurposeDesign Patternsthis

我们将给大家介绍调解者模式,这个模式的目的是封装一组对象之间的相互作用,防止对象之间相互干扰,调解者(Mediator)在同事对象(Colleague)之间充当中间汇聚点。
同事对象之间应该保持松散耦合,避免一个对象直接明确指向另一个对象。在调解者模式下,对象的关系和依赖发生冲突时,我们可以使用调解者在耦合的对象之间协调工作流,依赖可以从同事朝调解者或从调解者向同事建立,这两个方向上的依赖都可以使用AbstractColleague或AbstractMediator中断。

 调解者和同事对象
图1 调解者和同事对象

对象不是孤立的,对象之间必须相互协作才能完成任务。虽然调解者模式可以限制对象之间的相互作用,但如果滥用,会致使编写聚合性类变得非常困难。举一个实用的例子,在领域驱动设计(Domain-Driven Design)中的服务就是实体之间的调解者。再举一个PHP相关的例子,Zend_Form装饰和过滤功能实际上可以看作是Zend_Form_Decorator和Zend_Filter实例之间的一个简单调解者,它们都使用Zend_Validate对象进行验证。

当调解者必须监听同事对象的事件时,它通常是作为观察者(Observer)实现的,产生一个黑板(blackboard)对象,一些同事写,另一些同事就读。来自同事的事件被推向调解者,再由调解者将其转发给其它订阅的同事,同事之间不需要相互了解,这个架构成功用于随Zend框架发布的Dojo JavaScript库。这个模式的另一个好处是对象的变化包含在计算方法中,可以通过配置不同的调解者实现这一目标,但实例化相关对象将是一个松散的操作,不同容器和工厂之间的协作关系将是分散的。参与者:

◆同事(Colleague):重点是它的职责,它只与一个调解者Mediator或AbstractMediator通信。

◆调解者(Mediator):协同多个Colleagues(AbstractColleagues)共同工作。

◆AbstractMediator,AbstractColleague:从这些角色的真实实现解耦的可选接口,可能不止一个AbstractColleague角色。

下面的代码实现了一个表单输入的过滤过程,类似于Zend_Form_Element功能。

调解者和同事对象
Colleague objects should be loosely coupled to avoid one object pointing directly to another object. In the mediator mode, when the relationships and dependencies of objects conflict, we can use the mediator to coordinate the workflow between coupled objects. Dependencies can be established from colleagues to the mediator or from the mediator to colleagues in both directions. Dependencies can be broken using AbstractColleague or AbstractMediator.
Figure 1 Mediator and colleague objects
Objects are not isolated, and objects must cooperate with each other to complete tasks. Although the mediator pattern can limit the interaction between objects, if abused, it can make writing aggregate classes very difficult. To give a practical example, services in Domain-Driven Design are mediators between entities. To give another PHP-related example, the Zend_Form decoration and filtering functions can actually be seen as a simple mediator between Zend_Form_Decorator and Zend_Filter instances, both of which use Zend_Validate objects for validation.
When the mediator must listen to events on colleague objects, it is usually implemented as an Observer, producing a blackboard object for some colleagues to write and others to read. Events from colleagues are pushed to the mediator, who then forwards them to other subscribed colleagues. Colleagues do not need to know each other. This architecture is successfully used in the Dojo JavaScript library released with the Zend Framework. Another benefit of this pattern is that the changes to the object are contained in the calculation method. This can be achieved by configuring different mediators, but instantiating related objects will be a loose operation, and the collaborative relationship between different containers and factories will is decentralized. Participants:
◆Colleague: The focus is on its responsibilities, it only communicates with one mediator, Mediator or AbstractMediator.
◆Mediator: Work together with multiple Colleagues (AbstractColleagues).
◆AbstractMediator, AbstractColleague: Optional interfaces decoupled from the real implementation of these roles, there may be more than one AbstractColleague role.
The following code implements a form input filtering process, similar to the Zend_Form_Element function.
/**   * Colleague.  */ class NullFilter implements Filter { public function filter($value) { return $value ? $value : ; } } /**   * Colleague.  */ class HtmlEntitiesFilter implements Filter {        public function filter($value)                                                                                                                                                           🎜>
protected We will introduce to you the Mediator Pattern. The purpose of this pattern is to encapsulate the interaction between a group of objects and prevent the objects from interfering with each other. The Mediator (Mediator) acts as an intermediary between Colleague objects (Colleague). convergence point.

Colleague objects should be loosely coupled and avoid

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478778.htmlTechArticleWe will introduce to you the mediator pattern. The purpose of this pattern is to encapsulate the interaction between a group of objects. To prevent objects from interfering with each other, the mediator (Mediator) is used by colleague objects (...
Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

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 and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

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.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

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

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

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.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor