• 设计模式之适配器模式


        接着讲设计模式,这节讲适配器模式(Adapter Pattern)。

        在现实生活中,使用直流电的笔记本需要电源适配器才能安全接入交流电,不同语言之间的交流需要翻译官来做翻译,在程序中,我们也会遇到这种需要借助第三方进行适配的情景:当需要开发的具有某种业务功能的组件在现有的组件库中已经存在,但它们与当前系统的接口规范不兼容,如果重新开发这些组件成本又很高,这时用适配器模式能很好地解决这些问题。

        适配器模式的定义为:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。适配器模式分为类结构型模式和对象结构型模式两种,前者类之间的耦合度比后者高,且要求程序员了解现有组件库中的相关组件的内部结构,所以应用相对较少些。

        下面先看实例代码:

        类结构型模式:

    //新接口
    interface INewpower
    {
        void alternating_current ();
    }
    
    //旧接口
    interface IOldpower
    {
        void direct_current ();
    }
    
    //适配类
    class Laptop : IOldpower
    {
        public void direct_current ()
        {
            Console.WriteLine ("正在充电...");
        }
    }
    
    //适配器
    class PowerAdapter : Laptop, INewpower
    {
        //使用新接口中的方法,调用适配类中的方法
        public void alternating_current ()
        {
            direct_current ();
        }
    }
    
    //主方法中调用
    static void Main (string[] args)
    {
        INewpower np = new PowerAdapter ();
        np.alternating_current ();
    }

       对象结构型模式:

    //对象结构型模式的不同之处就在于对对象型适配器需要适配对象的实例,通过实例自己去调用方法
    class PowerAdapterOfObject : INewpower
    {
        private IOldpower op;
        public PowerAdapterOfObject (IOldpower op)
        {
            this.op = op;
        }
    
        public void alternating_current ()
        {
            op.direct_current ();
        }
    }
    
    //主方法中调用
    static void Main (string[] args)
    {
        INewpower npo = new PowerAdapterOfObject (new Laptop ());
        npo.alternating_current ();
    }

       适配器模式的优点是:客户端通过适配器可以透明地调用目标接口。复用了现存的类,程序员不需要修改原有代码而重用现有的适配者类。将目标类和适配者类解耦,解决了目标类和适配者类接口不一致的问题。在很多业务场景中符合开闭原则。

       缺点是:增加代码的复杂性,适配器多的情况下会使代码变的凌乱。

        个人公众号,热爱分享,知识无价。

  • 相关阅读:
    PHP多进程(四) 内部多进程
    STL map and multimap
    Understanding Function Objects
    Working with Bit Flags Using STL
    STL Algorithms
    STL set and multiset
    Understanding Smart Pointers
    More Effective C++ 学习笔记(1)
    Adaptive Container: stack and queue
    第一个 Python 程序
  • 原文地址:https://www.cnblogs.com/charlesmvp/p/13867824.html
Copyright © 2020-2023  润新知