加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php装饰器模式(decorator pattern)

发布时间:2020-12-13 16:08:00 所属栏目:PHP教程 来源:网络整理
导读:十一点了。 ? 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 definemultiple decorators,where each adds new functionality.

十一点了。

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

文件内容

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读