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

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

  • 相关阅读:
    Django forms组件
    Django 分页器
    Django Ajax
    Django 多表操作2
    js12种应该注意的地方
    Web自动化测试python环境中安装 --selenium安装、火狐和火狐驱动版本、谷歌和谷歌驱动版本、测试
    python学习-文件操作
    关于redis搭建环境
    扩展知识
    javascript之Banner图片焦点轮播
  • 原文地址:https://www.cnblogs.com/ontheway1024/p/7078455.html
Copyright © 2011-2022 走看看