张德长

导航

设计模式之:桥接模式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 2022-04-03 22:30  张德长  阅读(46)  评论(0编辑  收藏  举报