PHP 代码简洁之道(小结)(12)

abstract class Adapter
{
  protected $name;

  public function getName(): string
  {
    return $this->name;
  }
}

class AjaxAdapter extends Adapter
{
  public function __construct()
  {
    parent::__construct();

    $this->name = 'ajaxAdapter';
  }
}

class NodeAdapter extends Adapter
{
  public function __construct()
  {
    parent::__construct();

    $this->name = 'nodeAdapter';
  }
}

class HttpRequester
{
  private $adapter;

  public function __construct(Adapter $adapter)
  {
    $this->adapter = $adapter;
  }

  public function fetch(string $url): Promise
  {
    $adapterName = $this->adapter->getName();

    if ($adapterName === 'ajaxAdapter') {
      return $this->makeAjaxCall($url);
    } elseif ($adapterName === 'httpNodeAdapter') {
      return $this->makeHttpCall($url);
    }
  }

  private function makeAjaxCall(string $url): Promise
  {
    // request and return promise
  }

  private function makeHttpCall(string $url): Promise
  {
    // request and return promise
  }
}

好的:

interface Adapter
{
  public function request(string $url): Promise;
}

class AjaxAdapter implements Adapter
{
  public function request(string $url): Promise
  {
    // request and return promise
  }
}

class NodeAdapter implements Adapter
{
  public function request(string $url): Promise
  {
    // request and return promise
  }
}

class HttpRequester
{
  private $adapter;

  public function __construct(Adapter $adapter)
  {
    $this->adapter = $adapter;
  }

  public function fetch(string $url): Promise
  {
    return $this->adapter->request($url);
  }
}

里氏代换原则 (LSP)

这是一个简单概念的可怕术语。它通常被定义为 “如果 S 是 T 的一个子类型,则 T 型对象可以替换为 S 型对象”
(i.e., S 类型的对象可以替换 T 型对象) 在不改变程序的任何理想属性的情况下 (正确性,任务完成度,etc.)." 这是一个更可怕的定义.
这个的最佳解释是,如果你有个父类和一个子类,然后父类和子类可以互换使用而不会得到不正确的结果。这或许依然令人疑惑,所以我们来看下经典的正方形 - 矩形例子。几何定义,正方形是矩形,但是,如果你通过继承建立了 “IS-a” 关系的模型,你很快就会陷入麻烦。.

不好的:

class Rectangle
{
  protected $width = 0;
  protected $height = 0;

  public function render(int $area): void
  {
    // ...
  }

  public function setWidth(int $width): void
  {
    $this->width = $width;
  }

  public function setHeight(int $height): void
  {
    $this->height = $height;
  }

  public function getArea(): int
  {
    return $this->width * $this->height;
  }
}

class Square extends Rectangle
{
  public function setWidth(int $width): void
  {
    $this->width = $this->height = $width;
  }

  public function setHeight(int $height): void
  {
    $this->width = $this->height = $height;
  }
}

/**
 * @param Rectangle[] $rectangles
 */
function renderLargeRectangles(array $rectangles): void
{
  foreach ($rectangles as $rectangle) {
    $rectangle->setWidth(4);
    $rectangle->setHeight(5);
    $area = $rectangle->getArea(); // BAD: Will return 25 for Square. Should be 20.
    $rectangle->render($area);
  }
}

$rectangles = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles($rectangles);


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4018.html