十一点了。
<?php /* The decorator pattern allows behavior to be added to an individual object instance, without affecting the behavior of other instances of the same class. We can define multiple decorators, where each adds new functionality. */ interface LoggerInterface { public function log($message); } class Logger implements LoggerInterface { public function log($message) { file_put_contents(‘app.log‘, $message, FILE_APPEND); } } abstract class LoggerDecorator implements LoggerInterface{ protected $logger; public function __construct(Logger $logger) { $this->logger = $logger; } abstract public function log($message); } class ErrorLoggerDecorator extends LoggerDecorator { public function log($message) { $this->logger->log(‘ERROR: ‘ . $message); } } class WarningLoggerDecorator extends LoggerDecorator { public function log($message) { $this->logger->log(‘WARNING: ‘ . $message); } } class NoticeLoggerDecorator extends LoggerDecorator { public function log($message) { $this->logger->log(‘NOTICE: ‘ . $message); } } $logger = new Logger(); $logger->log(‘Resource not found.‘ . PHP_EOL); $logger = new Logger(); $logger = new ErrorLoggerDecorator($logger); $logger->log(‘Invalid user role.‘ . PHP_EOL); $logger = new Logger(); $logger = new WarningLoggerDecorator($logger); $logger->log(‘Missing address parameters.‘ . PHP_EOL); $logger = new Logger(); $logger = new NoticeLoggerDecorator($logger); $logger->log(‘Incorrect type provided.‘ . PHP_EOL); ?>
文件内容
原文地址:https://www.cnblogs.com/aguncn/p/11182574.html
时间: 2024-11-08 21:11:37