1.利用组件编程模式,防止冗余

<?php
class Action {
  private $name;
  public function __construct($name) {
    $this->name = $name;
  }
  public function eat($food) {
    echo $this->name . " eat ". $food . ".\n";
  }
}

class Gender {
  private $gender;
  public function __construct($gender) {
    $this->gender= $gender;
  }
  public function getGender() {
    return $this->gender;
  }
}

class BullWhale {
  private $action;
  private $gender;
  public function __construct() {
    $this->action = new Action("Bull Whale");
    $this->gender = new Gender("Male");
  }
  public function eatFood($food) {
    $this->action->eat($food);
  }
  public function getGender() {
    return $this->gender->getGender();
  }
}

$bullWhale = new BullWhale();
$bullWhale->eatFood("fish");
echo $bullWhale->getGender() . "\n";

结果

Bull Whale eat fish. Male

BullWhale由Action和Gender组件构成,不同的类可以选择不同的组件组合,这样就不会造成类冗余了。


mmy123456
376 声望17 粉丝

有项目请联系:15201970281(毛毛)