{ echo "hello, " . $keyboard->getName() . "\n"; } } /** * */ class Computer { protected $_items = []; public function add(Unit $unit) { $this->_items[] = $unit; } /** * 调用各个组件的accept方法 */ public function accept(Visitor $visitor) { foreach ($this->_items as $item) { $item->accept($visitor); } } } $computer = new Computer(); $computer->add(new Cpu()); $computer->add(new Memory()); $computer->add(new Keyboard()); $printVisitor = new PrintVisitor(); $computer->accept($printVisitor);