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
    */
    
    

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

  • 相关阅读:
    eos合约案例导读
    eos TODO EOS区块链上EOSJS和scatter开发dApp
    电脑提示‘您需要来自Administration的权限才能对此文件夹进行更改’怎么删除文件
    ubuntu 设置全局代理
    eos开发实践
    eos博客
    如何在Ubuntu 18.04上安装Go
    parity密码
    Nodejs基础之redis
    完全搞懂事件
  • 原文地址:https://www.cnblogs.com/ontheway1024/p/7078455.html
Copyright © 2011-2022 走看看