zoukankan      html  css  js  c++  java
  • 适配器模式

    定义

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

    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实现类就是一种适配器。

  • 相关阅读:
    (精华)将json数组和对象转换成List和Map(小龙哥和牛徳鹤的对话)
    优先队列底层实现是堆(heap)(操作系统进程调度)
    (透彻理解)最精锐代码::堆的三种基本操作新建-插入-删除
    (考研)读者写者问题(附代码)
    (考研)黑电吃苹果同步互斥问题(附代码)
    (考研)哲学家进餐问题(附代码)
    (考研)吸烟者问题(赋代码)
    (考研)PV操作和信号量
    01.第一章_C++ Primer学习笔记_开始
    C++学习笔记
  • 原文地址:https://www.cnblogs.com/Saints/p/12662965.html
Copyright © 2011-2022 走看看