作用:将抽象部分与它的实现部分分离,使它们都可以独立地变化。
实现要点:分离和聚合。将一个对象分解成两个部分。它们之间用聚合来保持关系。
UML:
设计模式学习之桥接模式(Bridge)

代码:这里的例子是将电器的开关功能与其分离,以适应不同变化

    public  abstract class SW
{
public abstract void OpenandClose();
}
//单向开关
class SingleSW : SW
{
public override void OpenandClose()
{
Console.WriteLine(
"this is a single switch!");
}
}
//双向开关
class DoubleSW : SW
{
public override void OpenandClose()
{
Console.WriteLine(
"this is a double switch!!");
}
}

public abstract class El_Device
{
protected SW _switcher;
public SW switcher
{
set { _switcher = value; }
}
public virtual void OpenandClose()
{
_switcher.OpenandClose();
}
}
//冰箱类,扮演桥接的角色
public class frigde : El_Device
{
public override void OpenandClose()
{
_switcher.OpenandClose();
}
}
//-------------------------执行--------------------------
class Program
{
static void Main(string[] args)
{
//新飞冰箱是单向开关
El_Device xinfei = new frigde();
xinfei.switcher
= new SingleSW();
//美的冰箱是双向开关
El_Device meidi = new frigde();
meidi.switcher
= new DoubleSW();

xinfei.OpenandClose();
meidi.OpenandClose();
Console.ReadLine();
}
}

 
                    
            
                

相关文章:

  • 2021-12-17
  • 2021-11-21
  • 2021-05-19
  • 2021-09-11
  • 2021-10-14
  • 2021-06-22
猜你喜欢
  • 2022-12-23
  • 2021-06-07
  • 2021-04-29
  • 2022-01-15
  • 2022-01-01
  • 2022-01-14
相关资源
相似解决方案