设计模式-桥接模式

设计模式-策略模式

说明

桥接模式 (Bridge Pattern):将抽象与实现解耦,使得两者可以独立的变化


模式说明

在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,桥接模式就是应对这种多维度的变化
举例说明:人使用手机看视频 此时就有三个维度,什么类型的人、什么品牌的手机、什么类型的视频
抽象出人,手机,视频,分别实现。其中人作为最底层,使用手机看视频。

代码示例

<?php
/**
 * 桥接模式 (Bridge Pattern):将抽象与实现解耦,使得两者可以独立的变化
 */
//在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,桥接模式就是应对这种多维度的变化
//举例说明:人使用手机看视频 此时就有三个维度,什么类型的人、什么品牌的手机、什么类型的视频
//抽象出人,手机,视频,分别实现。其中人作为最底层,使用手机看视频。

/**
 * Interface Mobile 手机接口
 */
interface Mobile{
    function mType();
}

/**
 * Class xiaomi 小米手机
 */
class xiaomi implements  Mobile{

    function mType()
    {
       echo "小米手机";
    }
}

/**
 * Class huwei 华为手机
 */
class huwei implements  Mobile{

    function mType()
    {
        echo "华为手机";
    }
}

/**
 * Interface Video 视频类型接口
 */
interface Video {
    function vType();
}

/**
 * Class GameVideo 游戏视频类
 */
class GameVideo implements  Video{

    function vType()
    {
        echo "观看游戏视频";
    }
}

/**
 * Class LearnVideo 学习视频类
 */
class LearnVideo implements  Video{

    function vType()
    {
        echo "观看学习视频";
    }
}

/**
 * Interface People 人群接口
 */
interface People{
    function uses();
}

/**
 * Class Students 学生类
 */
class Students implements People{
    public $mobile;
    public $video;
    public function __construct($mobile,$video){
        $this->mobile = $mobile;
        $this->video = $video;
    }

    function uses()
    {
        echo "学生会使用";
        $this->mobile->mType();
        $this->video->vType();
    }
}

/**
 * Class Teaches 老师类
 */
class Teaches implements People{
    public $mobile;
    public $video;
    public function __construct($mobile,$video){
        $this->mobile = $mobile;
        $this->video = $video;
    }

    function uses()
    {
        echo "老师会使用";
        $this->mobile->mType();
        $this->video->vType();
    }
}


/**
 * Class Client 客户端连接 进行调用
 */
class Client{
    public static function main(){
        $mobile = new xiaomi();
        $video = new LearnVideo();
        $road = new Students($mobile,$video);
        $road->uses();
    }
}
Client::main();

结果:学生会使用小米手机观看学习视频

结尾

心如花木,向阳而生。

添加新评论