码迷,mamicode.com
首页 > Web开发 > 详细

php装饰器模式(decorator pattern)

时间:2019-07-14 00:23:55      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:provided   The   user role   img   function   nali   err   miss   protected   

十一点了。

<?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);
?>

文件内容

技术图片

php装饰器模式(decorator pattern)

标签:provided   The   user role   img   function   nali   err   miss   protected   

原文地址:https://www.cnblogs.com/aguncn/p/11182574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!