Heim  >  Artikel  >  Backend-Entwicklung  >  浅析php适配器模式(Adapter),浅析adapter_PHP教程

浅析php适配器模式(Adapter),浅析adapter_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:13:191229Durchsuche

浅析php适配器模式(Adapter),浅析adapter

前几篇介绍了设计模式的特性并且详细讲解了4种创建型模式,创建型模式是负责如何产生对象实例的,接下来讲讲结构型模式。

一、什么是结构型模式

结构型模式是解析类和对象的内部结构和外部组合,通过优化程序结构解决模块之间的耦合问题。

二、结构型模式的种类

适配器模式
桥接模式
装饰模式
组合模式
外观模式
享元模式
代理模式

1、 适配器模式(Adapter)
将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本的由于接口不兼容而不能一起工作的那些类可以一起工作。
应用场景:老代码接口不适应新的接口需求,或者代码很多很乱不便于继续修改,或者使用第三方类库。

代码实现

复制代码 代码如下:

//老的代码    
class User {   
    private $name;   
    function __construct($name) {   
        $this->name = $name;   
    }   
    public function getName() {   
        return $this->name;   
    }   
}   

//新代码,开放平台标准接口   
interface UserInterface {   
    function getUserName();   
}   
class UserInfo implements UserInterface {   
    protected $user;   
    function __construct($user) {   
        $this->user = $user;   
    }   
    public function getUserName() {   
        return $this->user->getName();   
    }   
}   

$olduser = new User('张三');   
echo $olduser->getName()."n";   
$newuser = new UserInfo($olduser);   
echo $newuser->getUserName()."n";   

 注意点:这里的新接口使用了组合方式,UserInfo内部有一个成员变量保存老接口User对象,模块之间是松耦合的,这种结构其实就是组合模式。不要使用继承,虽然UserInfo继承User也能达到同样的目的,但是耦合度高,相互产生影响。

以上就是关于php设计模式中结构性模式中的适配器模式的全部内容了,小伙伴们是否了解清楚了呢,有问题就给我留言吧

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/917026.htmlTechArticle浅析php适配器模式(Adapter),浅析adapter 前几篇介绍了设计模式的特性并且详细讲解了4种创建型模式,创建型模式是负责如何产生对象实例...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn