zoukankan      html  css  js  c++  java
  • 设计模式PHP篇(三)————装饰器模式

    简单的用php实现了装饰器模式:

    <?php
    
    /**
    *简单的装饰器模式
    */
    class PrintText
    {
    	protected $decorators = [];
    
    	public function print()
    	{
    		$this->before();
    		echo "hello world" . PHP_EOL;
    		$this->after();
    	}
    
    	public function addDecorators(Decorator $decorator)
    	{	
    		$this->decorators[] = $decorator;
    
    	}
    
    	protected function before()
    	{
    		foreach ($this->decorators as $key => $value) {
    			$value->before();
    		}
    	}
    
    	//使用栈的方式,先进后出
    	protected function after()
    	{
    		 $decorators = array_reverse($this->decorators);
    		foreach($decorators as $key => $value){
    			$value->after();
    		}
    	}
    
    }
    
    interface Decorator
    {
    
    	public function before();
    	public function after();
    
    }
    
    class Font implements Decorator
    {
    	public function before()
    	{
    		echo "fonts before" . PHP_EOL;
    	}
    
    	public function after()
    	{
    		echo "fonts after" . PHP_EOL;
    	}
    }
    
    class Color implements Decorator
    {
    	public function before()
    	{
    		echo "color before" . PHP_EOL;
    	}
    
    	public function after()
    	{
    		echo "color after" . PHP_EOL;
    	}
    }
    
    $print = new PrintText();
    $print->addDecorators(new Font());
    $print->addDecorators(new Color());
    
    $print->print();
    
    
    //output results
    /**
    fonts before
    color before
    hello world
    color after
    fonts after
    */
    
    

    代码比较简单,如果有什么问题,还请不吝赐教。

  • 相关阅读:
    我知道点redis-数据结构与对象
    白帽子-第十四章 PHP安全
    白帽子-第二篇 客户端脚本安全
    网络编程
    inline的作用
    Windows静态库和动态库区别
    简单实现图片上传预览
    Java 通用正则表达式
    C#+Mysql 图片数据存储
    FileUpload转换为字节
  • 原文地址:https://www.cnblogs.com/ontheway1024/p/7078455.html
Copyright © 2011-2022 走看看