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组件构成,不同的类可以选择不同的组件组合,这样就不会造成类冗余了。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。