適配器

類適配

<?php
interface Target {
    public function hello();

    public function world();
}

class Adaptee {
    public function greet() {
        print_ln(__METHOD__);
    }

    public function world() {
        print_ln(__METHOD__);
    }
}

/**
* 對 target 接口 和 adaptee 具體實現進行適配
* 所有的適配細節對client透明
*/
class Adapter extends Adaptee implements Target {
    public function hello() {
        $this->greet();
    }
}

class Client {
    public static function main() {
        //$o = new Target();
        $o = new Adapter();
        $o->hello();
        $o->world();
    }
}

Client::main();

對象適配

<?php
interface Target {
    public function hello();

    public function world();
}

class Adaptee {
    public function greet() {
        print_ln(__METHOD__);
    }

    public function world() {
        print_ln(__METHOD__);
    }
}

/**
* 通過包裝Adaptee對象 對 target 接口 和 adaptee 具體實現適配
* client可隨意選擇合適的adaptee進行工作
* 必須要在Adapter中手動時間所有Target接口,具體工作由adaptee完成
*/
class Adapter implements Target {
    private $_adaptee;

    public function __construct(Adaptee $adaptee) {
        $this->_adaptee = $adaptee;
    }

    public function hello() {
        $this->_adaptee->greet();
    }

    public function world() {
        $this->_adaptee->world();
    }
}

class Client {
    public static function main() {
        $o = new Adapter(new Adaptee());
        $o->hello();
        $o->world();
    }
}

Client::main();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章