通过组合模拟多重继承。

在PHP中不支持多重继承,如果我们向使用多个类的方法而实现代码重用有什么办法么?

那就是组合。在一个类中去将另外一个类设置成属性。

下面的例子,模拟了多重继承。

接口实例

写一个概念性的例子。 我们设计一个在线销售系统,用户部分设计如下: 将用户分为,NormalUser, VipUser, InnerUser 三种。要求根据用户的不同折扣计算用户购买产品的价格。并要求为以后扩展和维护预留空间。

代码如下:
{
    public function getName();
    public function setName($_name);
    public function getDiscount();
}
abstract class AbstractUser implements User
{
    private $name = "";
    protected  $discount = 0;
    protected  $grade = "";
    function __construct($_name) {
        $this->setName($_name);
    }
    function getName() {
        return $this->name;
    }
    function setName($_name) {
    $this->name = $_name;
    }
    function getDiscount() {
        return $this->discount;
    }
    function getGrade() {
        return $this->grade;
    }
}
class NormalUser extends AbstractUser
{
    protected $discount = 1.0;
    protected $grade = "Normal";
}
class VipUser extends AbstractUser
{
    protected $discount = 0.8;
    protected $grade = "VipUser";
}
class InnerUser extends AbstractUser
{
    protected $discount = 0.7;
    protected $grade = "InnerUser";
}
interface Product
{
    function getProductName();
    function getProductPrice();
}
interface Book extends Product
{
    function getAuthor();
}
class BookOnline implements Book
{
    private $productName;
    protected $productPrice;
    protected $Author;
    function __construct($_bookName) {
        $this->productName = $_bookName;
    }
    function getProductName() {
        return $this->productName;
    }
    function getProductPrice() {
        $this->productPrice = 100;
        return $this->productPrice;
    }
    public function getAuthor() {
        $this->Author = "chenfei";
        return $this->Author;
    }
}
class Productsettle
{
    public static function finalPrice(User $_user, Product $_product, $number) {
        $price = $_user->getDiscount() * $_product->getProductPrice() * $number;
        return $price;
    }
}
$number = 10;
$book = new BookOnline("设计模式");
$user = new NormalUser("tom");
$price = Productsettle::finalPrice($user, $book, $number);
$str = "您好,尊敬的" . $user->getName() . "
";
$str .= "您的级别是" . $user->getGrade() . "
";
$str .= "您的折扣是" . $user->getDiscount() . "
";
$str .= "您的价格是" . $price;
echo $str;
?>


10-03 07:36