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

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

  • 相关阅读:
    可执行程序的装载
    stdafx.h的作用
    AI调色板
    3ds max输出图片
    3ds max移除几何体的线段
    3ds max删除了对象后,还是将原来所有对象输出的原因
    vs win32 & MFC 指针默认位置
    3ds max 分离对象
    PDF
    endnote设置文献第二行悬挂缩进办法
  • 原文地址:https://www.cnblogs.com/ontheway1024/p/7078455.html
Copyright © 2011-2022 走看看