初识
桥接模式(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();
}
}
优点
- 实现了抽象和实现部分的分离,从而极大的提高了系统的灵活性。
- 更好的可扩展性,抽象部分和实现部分可以分别独立扩展,而不会相互影响,大大的提供了系统的可扩展性。
缺点
- 桥接模式的引入增加了系统的理解和设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计和编程。
- 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围有一定的局限性。