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

    官方定义

    适配器模式(Adapter Pattern):将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作

    说明

    适配器根据使用方式不同,可以分为对象适配器、类适配器,推荐对象适配器

    案例

    在电商项目中会对接多个支付接口,不同的支付接口调用方式不一样,有些是http请求,有些是调用sdk,未来还可能有其他的方式,如何将这些支付接口对接到现有项目中
    不管你用什么方式去支付,客户端都希望你能给我一个统一的调用方式,这时就需要用适配器去适配客户端和支付接口
    案例中省略了支付公司SDK(被适配角色)

    客户端

    PayParameter payParameter = new PayParameter { OrderID = 10000, TotalPrice = 200M };
                //使用支付宝付款
                new AlipayBus().Pay(payParameter);
                //使用Paypal付款
                new PaypalBus().Pay(payParameter);
                //使用Adyen付款
                new AdyenBus().Pay(payParameter);
    

    Model

        public class PayParameter
        {
            public int OrderID { get; set; }
            public decimal TotalPrice { get; set; }
        }
        public class PayResult
        {
            /// <summary>
            /// 支付状态
            /// </summary>
            public int Code { get; set; }
            /// <summary>
            /// 交易流水号
            /// </summary>
            public string TX { get; set; }
        }
    

    PayBus(适配器):

        public interface IPayBus
        {
            PayResult Pay(PayParameter parameter);
        }
        public class PaypalBus : IPayBus
        {
            public PayResult Pay(PayParameter parameter)
            {
                //step1
                //step2
                //step3
                return new PayResult();
            }
        }
        public class AlipayBus : IPayBus
        {
            public PayResult Pay(PayParameter parameter)
            {
                //step1
                //step2
                //step3
                return new PayResult();
            }
        }
        public class AdyenBus : IPayBus
        {
            public PayResult Pay(PayParameter parameter)
            {
                //step1
                //step2
                //step3
                return new PayResult();
            }
        }
    
  • 相关阅读:
    java环境--JDK和Tomcat在linux上的安装和配置
    转载:jQuery的deferred对象详解
    js 模板引擎 -Art Template
    sublime text的快捷键
    Spring MVC 配置Controller详解
    转:几款免费的图表js插件
    tomcat manager详解
    C#判断一个string是否为数字
    调用摄像头并将其显示在UGUI image上自适应屏幕大小
    unity监测按下键的键值并输出+unity键值
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/13277505.html
Copyright © 2011-2022 走看看