php装饰器模式(decorator pattern)

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php装饰器模式(decorator pattern)相关的知识,希望对你有一定的参考价值。

十一点了。

<?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)的主要内容,如果未能解决你的问题,请参考以下文章

PHP 装饰器模式

PHP实现装饰器

php模式之装饰者模式学习

设计模式 —— 装饰器模式(Decorator Pattern)

设计模式:装饰器(Decorator)模式

装饰器模式--Decorator