桥接模式定义
桥接模式:解决类的多维度变化
将类的爆炸个数由M * N * L降为M+N+L个
代码实现
手机沿着操作系统和品牌两个维度发生了变化
public interface ISystem
{
string System();
string Version();
}
public class AndroidSystem : ISystem
{
public string System()
{
return "Android";
}
public string Version()
{
return "6.0";
}
}
public class IOSSystem : ISystem
{
public string System()
{
return "IOS";
}
public string Version()
{
return "9.4";
}
}
public class WinphoneSystem : ISystem
{
public string System()
{
return "Winphone";
}
public string Version()
{
return "10.0";
}
}
以上是系统抽象类和具体的系统实现类。
/// <summary>
/// 抽象父类
/// </summary>
public abstract class BasePhoneBridge
{
public ISystem SystemVersion { get; set; }
/// <summary>
/// 打电话
/// </summary>
public abstract void Call();
/// <summary>
/// 发短信
/// </summary>
public abstract void Text();
}
public class GalaxyBridge : BasePhoneBridge
{
public override void Call()
{
Console.WriteLine("Use OS {0}.{1}.{2} Call", this.GetType().Name, this.SystemVersion.System(), this.SystemVersion.Version());
}
public override void Text()
{
Console.WriteLine("Use OS {0}.{1}.{2} Text", this.GetType().Name, this.SystemVersion.System(), this.SystemVersion.Version());
}
}
public class LumiaBridge : BasePhoneBridge
{
public override void Call()
{
Console.WriteLine("Use OS {0}.{1}.{2} Call", this.GetType().Name, this.SystemVersion.System(), this.SystemVersion.Version());
}
public override void Text()
{
Console.WriteLine("Use OS {0}.{1}.{2} Text", this.GetType().Name, this.SystemVersion.System(), this.SystemVersion.Version());
}
}
public class iPhoneBridge : BasePhoneBridge
{
public override void Call()
{
Console.WriteLine("Use OS {0}.{1}.{2} Call", this.GetType().Name, this.SystemVersion.System(), this.SystemVersion.Version());
}
public override void Text()
{
Console.WriteLine("Use OS {0}.{1}.{2} Text", this.GetType().Name, this.SystemVersion.System(), this.SystemVersion.Version());
}
}
调用方代码如下:
ISystem android = new AndroidSystem();
ISystem ios = new IOSSystem();
ISystem winphone = new WinphoneSystem();
{
BasePhoneBridge phone = new GalaxyBridge();
phone.SystemVersion = android;
phone.Call();
phone.Text();
}
{
BasePhoneBridge phone = new GalaxyBridge();
phone.SystemVersion = ios;
phone.Call();
phone.Text();
}
{
BasePhoneBridge phone = new GalaxyBridge();
phone.SystemVersion = winphone;
phone.Call();
phone.Text();
}
要点总结
桥接模式大大降低了类膨胀的个数,但是会让调用方变得复杂一些,需要对类的细节了解的更多。