PHP之装饰器模式

来源:互联网 发布:java将链接生成二维码 编辑:程序博客网 时间:2024/04/27 18:53
<?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());
?>
原创粉丝点击