桥接模式-结构型设计模式 [PHP]

解耦一个对象的实现与抽象,这样两者可以独立地变化。\n对一个功能进行拆分成两个具体对象,通过构造函数或者方法传递桥接起来两个对象

通过传递另外对象来实现功能,本身保留抽象方法给子类去独立实现

abstract class Service\n{\n    protected Formatter $implementation;\n    public function __construct(Formatter $printer)\n    {\n        $this->implementation = $printer;\n    }\n\n    public function setImplementation(Formatter $printer)\n    {\n        $this->implementation = $printer;\n    }\n    abstract public function get(): string;\n}

两个子类实现同一个方法,不同的功能

class HelloWorldService extends Service\n{\n    public function get(): string\n    {\n        return $this->implementation->format(\'Hello World\');\n    }\n}\nclass PingService extends Service\n{\n    public function get(): string\n    {\n        return $this->implementation->format(\'pong\');\n    }\n}

具体的功能实现由另外的独立类来做,这样两个就可以独立变化了

interface Formatter\n{\n    public function format(string $text): string;\n}\nclass PlainTextFormatter implements Formatter\n{\n    public function format(string $text): string\n    {\n        return $text;\n    }\n}

使用,现在它本身可以通过子类独立变化,具体功能类可以传递进来,两者也是各自独立

$service = new HelloWorldService(new PlainTextFormatter());\n$service->get();

发表回复