<?php /* * 用一个类来装饰另一个类,动态的给一个对象增加一些额外功能,这些功能一般是在这个对象调用方法前或方法后 * 比如我们要给User类增加一个登陆日志的功能 */ // 抽象构件 abstract class Component { abstract public function login($time); } // user类 class User extends Component { private $login_time; public function login($time) { $this->login_time = $time; } } // 装饰器 class LogDecorate extends Component { private $user; private $time; /** * Log constructor. */ public function __construct(User $user) { $this->user = $user; } public function login($time) { $this->user->login($time); $this->log($time); } public function log($time) { echo sprintf("Log: login %d",$time) . PHP_EOL; } } $user = new User(); $log = new LogDecorate($user); $log->login(time());
时间: 2024-10-22 02:12:00