java组合模式_组合模式

PHP 实现:

/**

* Class Employee

* 雇员类

*/

class Employee

{

private $_name;

private $_dept;//部门

private $_salary;//薪水

private $_subordinates;//下属

public function __construct(string $name, string $dept, int $sal)

{

$this->_name = $name;

$this->_dept = $dept;

$this->_salary = $sal;

$this->_subordinates = [];

}

public function add(Employee $employee)

{

array_push($this->_subordinates, $employee);

}

public function remove(Employee $employee)

{

$this->_subordinates = array_filter($this->_subordinates, function ($v) use ($employee) {

return ($employee != $v);

});

}

public function getSubordinates()

{

return $this->_subordinates;

}

public function __toString()

{

// TODO: Implement __toString() method.

return "Employee: [name: " . $this->_name . ",dept: " . $this->_dept . ",salary: " . $this->_salary . "]";

}

}

class Demo

{

public static function main()

{

$CEO = new Employee("John", "CEO", 30000);

$headSales = new Employee("Robert", "Head Sales", 20000);

$headMarketing = new Employee("Michel", "Head Marketing", 20000);

$clerk1 = new Employee("Laura", "Marketing", 10000);

$clerk2 = new Employee("Bob", "Marketing", 10000);

$salesExecutive1 = new Employee("Richard", "Sales", 10000);

$salesExecutive2 = new Employee("Rob", "Sales", 10000);

$CEO->add($headSales);

$CEO->add($headMarketing);

$headSales->add($salesExecutive1);

$headSales->add($salesExecutive2);

$headMarketing->add($clerk1);

$headMarketing->add($clerk2);

echo $CEO . PHP_EOL;

$headMarketing->remove($clerk2);

foreach ($CEO->getSubordinates() as $employee) {

echo '-' . $employee . PHP_EOL;

foreach ($employee->getSubordinates() as $e) {

echo '---' . $e . PHP_EOL;

}

}

}

}

Demo::main();

泡水鱼干

泡水鱼干

626***755@qq.com9个月前 (05-13)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值