编程知识 cdmana.com

Combination patterns of PHP design patterns

Flat management is popular in Internet companies , That is, the management level should be less than or no more than three levels , As a bottom layer farmer , Yours CEO It's different from your rank 3 Within layer . But a lot of traditional businesses , There will be a very deep hierarchy , From the data structure , This kind of organizational structure grouped by functions is very much like a tree . Today's organizational structure is very similar to that of the enterprise structure .

Gof Class diagram and explanation

GoF Definition : Combine objects into a tree structure to represent “ part - whole ” Hierarchical structure .Composite Make the use of single object and composite object consistent

GoF Class diagram

 Portfolio model

Code implementation
abstract class Component
{
    protected $name;

    public function __construct($name){
        $this->name = $name;
    }
    
    abstract public function Operation(int $depth);

    abstract public function Add(Component $component);

    abstract public function Remove(Component $component);
}

Abstract composition node declaration , When appropriate, implement the default behavior of the common interface for all classes , Is the parent of all child nodes .

class Composite extends Component
{
    private $componentList;

    public function Operation($depth)
    {
        echo str_repeat('-', $depth) . $this->name . PHP_EOL;
        foreach ($this->componentList as $component) {
            $component->Operation($depth + 2);
        }
    }

    public function Add(Component $component)
    {
        $this->componentList[] = $component;
    }

    public function Remove(Component $component)
    {
        $position = 0;
        foreach ($this->componentList as $child) {
            ++$position;
            if ($child == $component) {
                array_splice($this->componentList, ($position), 1);
            }
        }
    }

    public function GetChild(int $i)
    {
        return $this->componentList[$i];
    }
}

Specific node implementation classes , Save the reference of the subordinate node , Define the actual node behavior .

class Leaf extends Component
{
    public function Add(Component $c)
    {
        echo 'Cannot add to a leaf' . PHP_EOL;
    }
    public function Remove(Component $c)
    {
        echo 'Cannot remove from a leaf' . PHP_EOL;
    }
    public function Operation(int $depth)
    {
        echo str_repeat('-', $depth) . $this->name . PHP_EOL;
    }
}

Leaf node , The final node without child nodes .

  • Never look at the code , It's just the implementation of a tree
  • All child nodes and leaf nodes can process data , But the leaf node is the end point
  • You want users to ignore the difference between composite objects and individual objects , When using all objects in a composite structure uniformly , You should consider using a composite pattern
  • Users don't care whether they are dealing with a leaf node or a composite component , You don't have to write some choice statements to define combinations
  • Composite patterns allow customers to consistently use composite structures and individual objects

And then the example at the beginning of the article , In our organizational structure , When a person reaches the bottom of a task , It goes through multiple levels . I still prefer the traditional way of enterprise management together . Usually one director corresponds to more than one supervisor , One supervisor corresponds to many managers , One manager corresponds to several leaders , One team leader corresponds to many employees . When a notice is given , Staff at every level have to respond , And continue to send the notice to the subordinate staff , At the same time, get feedback from subordinates . such , We unconsciously completed the application of a combination pattern in practice . All of a sudden, I feel great , It feels like life has reached its peak !!

Complete code :https://github.com/zhangyue0503/designpatterns-php/blob/master/14.composite/source/composite.php

example

Text message , We can use this function over and over again . This is no exception . This time our website background function is to send short messages to different sub stations and users from different sources . ad locum , We're still focused on texting , We want to give you users with different channel roles but with unified behavior , Just send it , This kind of function seems not difficult !

SMS sending class diagram

 SMS sending combination mode version

Complete source code :https://github.com/zhangyue0503/designpatterns-php/blob/master/14.composite/source/composite-msg.php

<?php

abstract class Role
{
    protected $userRoleList;
    protected $name;
    public function __construct(String $name)
    {
        $this->name = $name;
    }

    abstract public function Add(Role $role);

    abstract public function Remove(Role $role);

    abstract public function SendMessage();
}

class RoleManger extends Role
{
    public function Add(Role $role)
    {
        $this->userRoleList[] = $role;
    }

    public function Remove(Role $role)
    {
        $position = 0;
        foreach ($this->userRoleList as $n) {
            ++$position;
            if ($n == $role) {
                array_splice($this->userRoleList, ($position), 1);
            }
        }
    }

    public function SendMessage()
    {
        echo " Start sending user roles :" . $this->name . ' All user messages under ', PHP_EOL;
        foreach ($this->userRoleList as $role) {
            $role->SendMessage();
        }
    }
}

class Team extends Role
{

    public function Add(Role $role)
    {
        echo " Group users can't add subordinates !", PHP_EOL;
    }

    public function Remove(Role $role)
    {
        echo " Group users have no subordinates to delete !", PHP_EOL;
    }

    public function SendMessage()
    {
        echo " Group user roles :" . $this->name . ' 's SMS has been sent !', PHP_EOL;
    }
}

// root user 
$root = new RoleManger(' Website users ');
$root->add(new Team(' Master site user '));
$root->SendMessage();

//  Social section 
$root2 = new RoleManger(' Social section ');
$managerA = new RoleManger(' Forum user ');
$managerA->add(new Team(' Beijing forum users '));
$managerA->add(new Team(' Shanghai forum users '));

$managerB = new RoleManger('sns user ');
$managerB->add(new Team(' Beijing sns user '));
$managerB->add(new Team(' Shanghai sns user '));

$root2->add($managerA);
$root2->add($managerB);
$root2->SendMessage();

explain
  • When I want to send users of forum section , I can freely add leaf nodes of local stations to control the sending objects
  • You can put the whole $root2 As a whole , Different sections and regions are seen as parts
  • This combination can go all the way down , Until the deep leaf node ends , Of course, this degree is controlled by ourselves , It's very clear

Next time, we'll see

The biggest feature of combination mode is that it can make leaf nodes or child nodes combine and extend infinitely . Can form a variety of different combinations , But it can also ensure that all changes will not depart from their ancestors . Let the whole recursion be in a controllable range , Very cattle X Well !! What we will learn next is Intermediary model , What's the difference between it and the real estate agents we often deal with ? Don't worry. , Chat next time !

Each media platform can search 【 Hard core project manager 】

版权声明
本文为[Hard core project manager]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225104724963f.html

Scroll to Top