【C#设计模式(7)——桥接模式(Bridge Pattern)】
前言
桥接模式的主要作用是将抽象部分和实现部分分离,使它们可以独立地进行扩展、修改和重用,从而增加了系统的灵活性和可维护性。
代码
// 桥接口
public interface IBridge
{
void Create();
}
//石桥
public class StoneBridge : IBridge
{
public void Create()
{
Console.WriteLine("The bridge is made of stone.");
}
}
//刚桥
public class SteelBridge : IBridge
{
public void Create()
{
Console.WriteLine("The bridge is made of steel.");
}
}
//抽象桥类型
public abstract class BridgeType
{
protected IBridge bridge;
protected BridgeType(IBridge bridge)
{
this.bridge = bridge;
}
public abstract void Create();
}
//拱桥类型
public class ArchBridge : BridgeType
{
public ArchBridge(IBridge bridge) : base(bridge){}
public override void Create()
{
Console.WriteLine("Creating an arch bridge. ");
bridge.Create();
}
}
//钢架桥
public class RigidFrameBridge : BridgeType
{
public RigidFrameBridge(IBridge bridge) : base(bridge){}
public override void Create()
{
Console.WriteLine("Created a steel bridge.");
bridge.Create();
}
}
/*
* 结构型模式:Structural Pattern
* 桥接模式:Bridge Pattern
*/
internal class Program
{
static void Main(string[] args)
{
IBridge stone = new StoneBridge();
IBridge steel = new SteelBridge();
BridgeType archBridge = new ArchBridge(stone);
BridgeType rigidFrameBride = new RigidFrameBridge(steel);
archBridge.Create();
rigidFrameBride.Create();
Console.ReadLine();
}
}