您的位置:首页 > 编程语言 > PHP开发

PHP之装饰器模式

2008-09-08 16:00 204 查看
<?php
abstract class AbstractRating {
    protected $decoratable;                  
    public function __construct( $decoratable ) {             
        $this -> decoratable = $decoratable;         
    }                
    abstract public function getRating();     
}      

class PoorRating extends AbstractRating {         
    protected $rating = 1;                  
    public function __construct($decoratable) {             
        parent::__construct( $decoratable );         
    }                  
    public function getRating() {             
        return $this -> decoratable -> getRating() + $this -> rating;         
    }    
}          

class AverageRating extends AbstractRating {         
    protected $rating = 2;                  
    public function __construct( $decoratable ) {             
        parent::__construct( $decoratable );         
    }                  
    public function getRating() {             
        return $this -> decoratable -> getRating() + $this -> rating;         
    }     
}          

class GoodRating extends AbstractRating {         
    protected $rating = 3;                  
    public function __construct( $decoratable ) {             
        parent::__construct( $decoratable );         
    }                  
    public function getRating() {             
        return $this -> decoratable -> getRating() + $this -> rating;         
    }     
}          

class Ratings {         
    private $rating = 3;                  
    public function __construct() { }                  
    public function getRating() {             
        return $this -> rating; // typeof integer         
    }     
}          
$rating = new GoodRating( new AverageRating( new Ratings ) );     // we are decorating the Ratings object     
echo($rating -> getRating());
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息