PHP Design Patterns intermediary model

On the back and said, we are often working outside of a group of people and have deep contacts, and that is the real estate agent. After graduating from college soon be able to buy a house in the second generation X favorite city is not within our scope to consider Kazakhstan. Since the need for long-term rental, then because of changes in work or life, the inevitable one or two years or three to five years and will play a 2000-2003 real estate agent. Sometimes, we do not necessarily know the information renters homeowners, homeowners do not know that our information, all by the agency for processing. Here, the agency has become a bridge of communication, in fact, this situation is like a homeowner in the field have gone abroad or thing and the house managed to complete the hands of intermediaries. Similar to this case, the code in the world, is a typical application of the Mediator pattern.

Gof class diagram and explanations

GoF Definition: mediation object that encapsulates a set of objects interact. Mediator keeping objects explicitly referring to each other, so that it loosely coupled, and can be independently varied interaction therebetween

FIG class GoF

Code
abstract class Mediator
{
    abstract public function Send(String $message, Colleague $colleague);
}

class ConcreteMediator extends Mediator
{
    public $colleague1;
    public $colleague2;

    public function Send(String $message, Colleague $colleague)
    {
        if ($colleague == $this->colleague1) {
            $this->colleague2->Notify($message);
        } else {
            $this->colleague1->Notify($message);
        }
    }
}

Abstracted from intermediaries and the specific implementation, where we assume there are fixed two colleagues class, let them talk to each other, so it's time to enter colleagues 1, went to call the Notify method, the equivalent is to allow the reception 2 1 to the messages sent by

abstract class Colleague
{
    protected $mediator;
    public function __construct(Mediator $mediator)
    {
        $this->mediator = $mediator;
    }

}

class ConcreteColleague1 extends Colleague
{
    public function Send(String $message)
    {
        $this->mediator->Send($message, $this);
    }
    public function Notify(String $message)
    {
        echo "同事1得到信息:" . $message, PHP_EOL;
    }
}

class ConcreteColleague2 extends Colleague
{
    public function Send(String $message)
    {
        $this->mediator->Send($message, $this);
    }
    public function Notify(String $message)
    {
        echo "同事2得到信息:" . $message;
    }
}

Colleagues and specific implementation class, where we make sure the point is, every class a colleague, known only to intermediaries who did not know another colleague class, which is characteristic of a mediator, the two sides do not know.

$m = new ConcreteMediator();

$c1 = new ConcreteColleague1($m);
$c2 = new ConcreteColleague2($m);

$m->colleague1 = $c1;
$m->colleague2 = $c2;

$c1->Send("吃过饭了吗?");
$c2->Send("没有呢,你打算请客?");

Call the client is relatively simple it!

  • This mode is not feeling very fit to do some communications products? Yes, social chat, sns, live like are appropriate, because this model is to allow decoupling between users, so that a user does not need to maintain all user objects associated
  • Because the user does not need to maintain the relationship, so it is the way to solve the problem of maintenance-many relationship between, at the same time, users do not need to modify the class to change relations have maintained a good package of user classes
  • However, intermediaries centralized maintenance may result in this class is too complex and large
  • Therefore, the model is not a panacea, be sure to clarify the choice to use the business scene
  • Mediator apply to a set of objects with well-defined but complex ways of communication occasion, and want to customize the behavior of a distributed across multiple classes, but do not want to generate too many occasions subclass

As an entrepreneur, he understands the importance of project management, project manager, is the role of a mediator in many occasions. From an organizational point of view, the beginning and end of a project, as I do not need to worry about who the boss is implemented by a specific code, I'm just trying to communicate to the project manager. Similarly, other auxiliary departments including finance, personnel, administration, etc., they do not care about who is going to write the code, but only need to exchange and project managers to understand the situation of the project and what needs to cooperate. The project team, people do write code? You do not need to know who will give him wages or attendance where the problem is, also, to all project managers fix it. So, the project manager responsible for project development, is a typical application of the Mediator pattern. Our mobile phone factory reason why the development is so fast, but also thanks to these project managers, asking them to eat a big meal at night to go slightly ~ ~ ~

Complete code: https://github.com/zhangyue0503/designpatterns-php/blob/master/15.mediator/source/mediator.php

Examples

This time we do not send text messages, a chat room to achieve it. A simple online chat room, the demand is to allow the user to enter the chat room can chat online, let's look at how to use the intermediary model to achieve this room now!

FIG Chat Room Class

Complete source code: https://github.com/zhangyue0503/designpatterns-php/blob/master/15.mediator/source/mediator-webchat.php

<?php

abstract class Mediator
{
    abstract public function Send($message, $user);
}

class ChatMediator extends Mediator
{
    public $users = [];
    public function Attach($user)
    {
        if (!in_array($user, $this->users)) {
            $this->users[] = $user;
        }
    }

    public function Detach($user)
    {
        $position = 0;
        foreach ($this->users as $u) {
            if ($u == $user) {
                unset($this->users[$position]);
            }
            $position++;
        }
    }

    public function Send($message, $user)
    {
        foreach ($this->users as $u) {
            if ($u == $user) {
                continue;
            }
            $u->Notify($message);
        }
    }
}

abstract class User
{
    public $mediator;
    public $name;

    public function __construct($mediator, $name)
    {
        $this->mediator = $mediator;
        $this->name = $name;
    }
}

class ChatUser extends User
{
    public function Send($message)
    {
        $this->mediator->Send($message . '(' . $this->name . '发送)', $this);
    }
    public function Notify($message)
    {
        echo $this->name . '收到消息:' . $message, PHP_EOL;
    }
}

$m = new ChatMediator();

$u1 = new ChatUser($m, '用户1');
$u2 = new ChatUser($m, '用户2');
$u3 = new ChatUser($m, '用户3');

$m->Attach($u1);
$m->Attach($u3);
$m->Attach($u2);

$u1->Send('Hello, 大家好呀!'); // 用户2、用户3收到消息

$u2->Send('你好呀!'); // 用户1、用户3收到消息

$m->Detach($u2); // 用户2退出聊天室

$u3->Send('欢迎欢迎!'); // 用户1收到消息
Explanation
  • There are not found, the mediator is this "chat room", it is to be passed by the transfer of information
  • Because here is not a fixed number of users, it is an array of maintenance, when a user sends a message, in addition to himself, other people have received this message
  • Chat room users can freely in and out, to be honest, this example has been almost like a really realize the function of the chat application oh
  • Sure enough intermediary model is really suitable for communications applications, however, if the user enters very much, $ users list will become bloated, oh, this is the problem described above where the intermediary model
Published 41 original articles · won praise 6 · views 50000 +

Guess you like

Origin blog.csdn.net/bujidexinq/article/details/104964311