Рубрики
Uncategorized

Тематическое исследование режима цепочки ответственности в шаблоне проектирования PHP

Автор оригинала: David Wong.

В этой статье описывается шаблон проектирования PHP шаблона цепочки ответственности. Подробности заключаются в следующем:

Атрибуты межзвездного оружия будут изменены с корректировкой баланса. Если это так, нам необходимо рассмотреть вопрос о снижении релевантности между событием и конкретной обработкой.

Например, в тот момент, когда будет сброшена атомная бомба, количество войск или зданий в радиусе поражения будет уменьшено. Однако с расстоянием от центральной точки степень повреждения различна, и повреждения разных видов оружия и зданий различны.

Проблемы, которые необходимо решить: Problems to be solved: At the moment when the atomic bomb is dropped, the disposal of the damage is handed over to the troops within the scope of the damage or to the building’s own methods. В момент, когда сброшена атомная бомба, ликвидация ущерба передается войскам в пределах нанесенного ущерба или собственным методам здания.

Мышление: Создайте интерфейс для всех войск или зданий для реализации.

Пример цепочки ответственности

php
  //Interface attacked by atomic bomb
  interface NuclearAttacked 
  {
    //The method to deal with the attack of atomic bomb, the parameters are the X and Y coordinates of the dropping point
    public function NuclearAttacked($x, $y);
  }

  //The base of the Terran, the interface to be attacked by the atomic bomb, other contents are not considered for the time being
  class CommandCenter implements NuclearAttacked 
  {
    //The method to deal with the attack of atomic bomb, the parameters are the X and Y coordinates of the dropping point
    public function NuclearAttacked($x, $y)
    {
      //According to the distance from the center of the atomic bomb, the reduced blood is defined. If it exceeds the remaining blood, it will be blown up
    }
  }

  //Cruiser (commonly known as Yamato), the realization of the atomic bomb attack interface, other content is not considered
  class Battlecruiser implements NuclearAttacked 
  {
    //The method to deal with the attack of atomic bomb, the parameters are the X and Y coordinates of the dropping point
    public function NuclearAttacked($x, $y)
    {
      //According to the distance from the center of the atomic bomb, the reduced blood is defined. If it exceeds the remaining blood, it will be blown up
    }
  }

  //Atomic bomb
  class Nuclear 
  {
    //Target of atomic bomb attack
    public $attackedThings;

    //Add objects attacked by atomic bomb
    public function addAttackedThings($thing)
    {
      //Add objects attacked by atomic bomb
      $this->attackedThings[] = $thing;
    }

    //In the method of atomic bomb explosion, the parameters are the X and Y coordinates of the dropping point
    public function blast($x, $y)
    {
      //Leave the explosion to all the people involved and let them handle it by themselves
      foreach ($this->attackedThings as $thing)
      {
        //Leave the explosion to all the people involved and let them handle it by themselves
        $thing->NuclearAttacked($x, $y);
      }
    }
  }

  //Create a new base object
  $CommandCenter = new CommandCenter();

  //Create a new cruiser object
  $Battlecruiser = new Battlecruiser();

  //Built an atomic bomb
  $Nuclear2 = new Nuclear();

  //Assuming successful launch, a base object and a cruiser object are in kill range at that moment
  $Nuclear2->addAttackedThings($CommandCenter);
  $Nuclear2->addAttackedThings($Battlecruiser);

  //Atomic bomb explosion, so that the event to those involved in the processing of the object, assuming that the X and Y coordinates of the drop point is 2353, 368
  $Nuclear2->blast(2353, 368);
?>

Краткое описание использования: Шаблон цепочки ответственности может оставить обработку события, включающего несколько объектов, самим объектам, чтобы снизить релевантность.

Краткое описание реализации: Вам нужен интерфейс для обработки событий, а затем позвольте всем объектам реализовать их.

Подробнее о содержании, связанном с PHP, заинтересованные читатели могут ознакомиться со специальными разделами этого веб-сайта: “Вводный учебник по объектно-ориентированному программированию PHP”, “Энциклопедия навыков работы с массивами PHP”, “Вводный учебник по базовой грамматике PHP”, “Краткое описание операций PHP и использования операторов”, “Краткое описание использования строк PHP”, “Вводный учебник по работе с базой данных PHP + MySQL” и “Общая работа с базой данных PHP”. Краткое изложение навыков письма

Я надеюсь, что эта статья будет полезна для программирования на PHP.