我正在尝试构建一个简单的组合模式示例。基本上输出将是每个部门员工的总智能。我创建了 3 种类型的员工和 2 个部门。请参阅以下代码:
员工类
abstract class Employee {
function addEmployee(Employee $employee){
}
function removeEmployee(){
}
abstract function showIntelligent();
}
奴才类
class Minion extends Employee {
function showIntelligent(){
return '100';
}
}
经理班
class Manager extends Employee {
function showIntelligent(){
return '150';
}
}
营业部班
class SalesDept extends Employee {
private $_deptEmployee=array();
function addEmployee(Employee $employee){
$this->_deptEmployee[]=$employee;
}
function removeEmployee(){
if(!empty($this->_deptEmployee)){
array_pop($this->_deptEmployee);
}else{
echo 'no employees in Sales Department';
}
}
function showIntelligent() {
$totalInt=0;
foreach ($this->_deptEmployee as $employee){
$totalInt += $employee->showIntelligent();
}
echo 'Total Intelligent of the Sales Department Employees is: '.$totalInt;
}
}
设计系班
class DesignDept extends Employee {
private $_deptEmployee=array();
function addEmployee(Employee $employee){
$this->_deptEmployee[]=$employee;
}
function removeEmployee(){
if(!empty($this->_deptEmployee)){
array_pop($this->_deptEmployee);
}else{
echo 'no employees in Design Department';
}
}
function showIntelligent() {
$totalInt=0;
foreach ($this->_deptEmployee as $employee){
$totalInt += $employee->showIntelligent();
}
echo 'Total Intelligent of the Design Department Employees is: '.$totalInt;
}
}
我的索引
$salesDpt=new SalesDept();
$salesDpt->addEmployee(new Manager());
$salesDpt->addEmployee(new Minion());
$salesDpt->addEmployee(new Minion());
$salesDpt->addEmployee(new GeneralManager());
$salesDpt->showIntelligent();
$DesignDpt=new DesignDept();
$DesignDpt->addEmployee(new Manager());
$DesignDpt->addEmployee(new Manager());
$DesignDpt->addEmployee(new Minion());
$DesignDpt->addEmployee(new Minion());
$DesignDpt->addEmployee(new Minion());
$DesignDpt->addEmployee(new Minion());
$DesignDpt->addEmployee(new Minion());
$DesignDpt->addEmployee(new Minion());
$DesignDpt->addEmployee(new Minion());
$DesignDpt->addEmployee(new GeneralManager());
$DesignDpt->showIntelligent();
看来我必须使用大量代码来添加新员工。这是一个好习惯吗?无论如何要改进它?感谢您的任何建议。