张德长

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

设计模式之:桥接模式BridgePattern的实现

  • 如果某个类存在两个维度的变化,通过桥接模式可以将两个维度分离出来,使两者可以独立扩展;
  • 桥接模式用一种巧妙地方式处理多层继承的问题,用抽象关联关系取代多层继承关系;
  • 将类之间的静态继承关系转换为动态的对象组合关系,符合组合原则;
  •  桥接模式更容易扩展,并且可以显著减少类的个数;
  • 如果一个类的两个维度分别是m和n,用多层继承则需要创建m*n个类,而桥接模式则只需要创建m+n+2个类,后面两个是抽象类或者接口;

类图with StarUML

像素类

internal class Matrix
{
//模拟像素矩阵
}

一个图像抽象类和4个实现类

internal abstract class Image
{
protected ImageImp imp;
//注入实现类接口对象
public void SetImageImp(ImageImp imp) { this.imp = imp; }
public abstract void ParseFile(string fileName);
}
internal class JPGImage : Image
{
public override void ParseFile(string fileName)
{
Matrix m = new Matrix();
imp.DoPaint(m);
Console.WriteLine($"{fileName},格式为JPG");
}
}
internal class PNGImage : Image
{
public override void ParseFile(string fileName)
{
Matrix m = new Matrix();
imp.DoPaint(m);
Console.WriteLine($"{fileName},格式为PNG");
}
}
internal class BMPImage : Image
{
public override void ParseFile(string fileName)
{
Matrix m = new Matrix();
imp.DoPaint(m);
Console.WriteLine($"{fileName},格式为BMP");
}
}
internal class GIFImage : Image
{
public override void ParseFile(string fileName)
{
Matrix m = new Matrix();
imp.DoPaint(m);
Console.WriteLine($"{fileName},格式为GIF");
}
}

一个操作系统接口和3个实现类

internal interface ImageImp
{
void DoPaint(Matrix m);
}
internal class WindowsImp : ImageImp
{
public void DoPaint(Matrix m) { Console.WriteLine("在Windows系统中显示图像"); }
}
internal class LinuxImp : ImageImp
{
public void DoPaint(Matrix m) { Console.WriteLine("在Linux系统中显示图像"); }
}
internal class UnixImp : ImageImp
{
public void DoPaint(Matrix m) { Console.WriteLine("在Unix系统中显示图像"); }
}

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="image" value ="BridgePattern.JPGImage"/>
<add key="os" value ="BridgePattern.WindowsImp"/>
</appSettings>
</configuration>

客户端

static void Main(string[] args)
{
//面向接口编程
Image image;
ImageImp imp;
//读取配置文件
string imageType = ConfigurationManager.AppSettings["image"];
string osType = ConfigurationManager.AppSettings["os"];
//反射生成对象
image = Assembly.Load("BridgePattern").CreateInstance(imageType) as Image;
imp = Assembly.Load("BridgePattern").CreateInstance(osType) as ImageImp;
image.SetImageImp(imp);
image.ParseFile("中国地图");
Console.Read();
}
}

运行结果

posted on   张德长  阅读(48)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示