适配器模式

定义

将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

UML 类图

实现

场景: 你有一个绘制柱状图组件,其他组件(客户)调用该组件完成柱状图的显示,有一天你希望使用功能更加丰富的的第三方图表组件,而第三方的图表组件API与你自己的柱状图组件不太相同,这时候可以使用适配器模式,将第三方绘图组件封装成其他组件(客户)需要的API类型。

目标接口

    public interface IBarChart
    {
        string Title { get; set; }
        List<string> XData { get; set; }
        List<int> YData { get; set; }
        void GenerateChart();
    }

目标接口实现

    public interface IBarChart
    {
        string Title { get; set; }
        List<string> XData { get; set; }
        List<int> YData { get; set; }
        void GenerateChart();
    }

不兼容的第三方图表组件

    public class ThirdPatryBarChart
    {
        public void DrawChart(string title, List<string> xData, List<int> yData)
        {
            Console.WriteLine($"ThirdParty Chart:Title:{title},X:{string.Join(",",xData)},Y:{string.Join(",",yData)}");
        }
    }

适配器

    public class BarChartAdapter : IBarChart
    {
        ThirdPatryBarChart _chart;

        public BarChartAdapter(ThirdPatryBarChart chart)
        {
            _chart = chart;
        }
        public string Title { get; set; }
        public List<string> XData { get; set; }
        public List<int> YData { get; set; }

        public void GenerateChart()
        {
            _chart.DrawChart(Title,XData,YData);
        }
    }

client

    class Program
    {
        static void Main(string[] args)
        {
            IBarChart myBarChart = new MyBar
            {
                Title = "MyChart",
                XData = new List<string> { "Level A", "Level B", "Level C" },
                YData = new List<int> { 100, 80, 65 }
            };

            myBarChart.GenerateChart();

            IBarChart thirdPartyBarChart = new BarChartAdapter(new ThirdPatryBarChart())
            {
                Title = "ThirdPartyChart",
                XData = new List<string> { "Level A", "Level B", "Level C" },
                YData = new List<int> { 90, 75, 60 }
            };

            thirdPartyBarChart.GenerateChart();
        }
    }

运行结果

    My Bar Chart:Title:MyChart,X:3,Y:3
    ThirdParty Chart:Title:ThirdPartyChart,X:Level A,Level B,Level C,Y:90,75,60

其他应用场景

开发中Service层依赖IRepository接口,每种数据对于数据访问的API不同,针对不同数据库IRepository实现类就是一种适配器。

posted @ 2020-04-08 21:33  青玄鸟  阅读(162)  评论(0编辑  收藏  举报