设计模式——桥接模式

初识

桥接模式(Bridge)是一种结构型设计模式。Bridge模式基于类的最小设计原则,通过使用封装、聚合及继承等行为让不同的类承担不同的职责。它的主要特点是把抽象(Abstraction)与行为实现(Implementation)分离开来,从而可以保持各部分的独立性以及应对他们的功能扩展。

结构

在这里插入图片描述

应用

电脑品牌分为:戴尔、联想、华硕、惠普等。而操作系统又分为windows,Linux等。我们画一个类图看看:
在这里插入图片描述
这时,如果往里面加惠普电脑,再加一个IOS系统。我们就需要添加三个类,并继承。如果我们添加更多的东西,工作量就会很大。我们用桥接模式来改善一下。
在这里插入图片描述

实现

class Program
{
     static void Main(string[] args)
     {
            Computer computer = new Dell();		//实例化Dell电脑

            computer.SetComputer(new Windows());
            computer.Print();					//调用Windows中的Print方法

            computer.SetComputer(new Linux());
            computer.Print();					//调用Linux中的Print方法

            computer = new Lenovo();			//实例化Lenovo电脑

            computer.SetComputer(new Windows());
            computer.Print();					//调用Windows中的Print方法

            computer.SetComputer(new Linux());
            computer.Print();					//调用Linux中的Print方法

            Console.Read();
     }
 }

abstract class OS
{
    public abstract void Print(); 
}

class Windows: OS
{
    public override void Print()
    {
        Console.WriteLine("Windows系统");
    }
}

class Linux: OS
{
    public override void Print()
    {
        Console.WriteLine("Linux系统");
    }
}

abstract class Computer
{
    protected OS os;

    public void SetComputer(OS os)
    {
        this.os = os;
    }

    public abstract void Print();
}

class Dell:Computer
{
    public override void Print()
    {
        os.Print();
    }
}

class Lenovo:Computer
{
    public override void Print()
    {
        os.Print();
    }
}

优点

  • 实现了抽象和实现部分的分离,从而极大的提高了系统的灵活性。
  • 更好的可扩展性,抽象部分和实现部分可以分别独立扩展,而不会相互影响,大大的提供了系统的可扩展性。

缺点

  • 桥接模式的引入增加了系统的理解和设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计和编程。
  • 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围有一定的局限性。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 18
    评论
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值