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

  • 相关阅读:
    600+ 道 Java面试题及答案整理(2021最新版)
    Spring Boot + Web Socket 实现扫码登录,这种方式太香了!!
    小团队适合引入 Spring Cloud 微服务吗?
    Netty 通道怎么区分对应的用户?
    软件开发打败了 80 %的程序员
    一个最简单的消息队列,带你理解 RabbitMQ!
    厉害了,Netty 轻松实现文件上传!
    Netty 是如何解决 TCP 粘包拆包的?
    图解 Git,一目了然!
    面试官:谈谈分布式一致性机制,我一脸懵逼。。
  • 原文地址:https://www.cnblogs.com/Saints/p/12662965.html
Copyright © 2011-2022 走看看