[PHP] 桥接模式-结构型设计模式
发布时间:2021-05-21 06:55:45 所属栏目:大数据 来源: https://www.jb51.cc
导读:解耦一个对象的实现与抽象,这样两者可以独立地变化。 对一个功能进行拆分成两个具体对象,通过构造函数或者方法传递桥接起来两个对象 ? 通过传递另外对象来实现功能,本身保留抽象方法给子类去独立实现 abstract class Service{ protected Formatter $impleme
解耦一个对象的实现与抽象,这样两者可以独立地变化。 ? 通过传递另外对象来实现功能,本身保留抽象方法给子类去独立实现 abstract class Service { protected Formatter $implementation; public function __construct(Formatter $printer) { $this->implementation = $printer; } function setImplementation(Formatter $printer) { $ $printer; } public function get(): string; } 两个子类实现同一个方法,不同的功能 HelloWorldService extends Service { { return $this->implementation->format('Hello World'); } } PingService extends Service { pong); } } 具体的功能实现由另外的独立类来做,这样两个就可以独立变化了 interface Formatter { public function format(string $text): ; } PlainTextFormatter implements Formatter { return $text; } } 使用,现在它本身可以通过子类独立变化,具体功能类可以传递进来,两者也是各自独立 $service = new HelloWorldService(new PlainTextFormatter()); $service->get(); ? (编辑:北几岛) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |