zoukankan      html  css  js  c++  java
  • [PHP] 桥接模式-结构型设计模式

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

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

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

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

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

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

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

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

    $service = new HelloWorldService(new PlainTextFormatter());
    $service->get();
  • 相关阅读:
    SVN中的Trunk、Tag、Brance的用法
    开发下载地址汇集
    Hessian原理分析
    Java中间件:淘宝网系统高性能利器
    linux进阶
    常见的Hadoop十大应用误解
    搜索引擎汇总
    bat薪酬
    常用的快速Web原型图设计工具
    apache kafka消息服务
  • 原文地址:https://www.cnblogs.com/taoshihan/p/13816696.html
Copyright © 2011-2022 走看看