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

    适配器模式:适配器模式允许将一个类的接口转换成客户期望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以一起工作。

    面向接口编程的原则:尽量将程序之中的参数,返回值,变量全都使用接口来代替。

    1:类适配器模式: 带来高耦合(不推荐)
    2:对象适配器模式:送耦合(推荐)

    适配器模式的应用:

    在.net之中复用com对象:
    --com对象不符合.net对象的接口
    --需要使用tlbimp.exe来创建一个runtime callable wrapper(RCW)以使其能够符合.net对象的接口。

    .net数据访问类(Adapter变体)
    --各种数据库并没有提供Dataset接口
    --使用dbDataAdapter可以将任何各种数据库访问到的数据适配到DataSet对象上

    集合类中队现有对象的排序
    --现有对象未实现IComparable接口
    --实现一个排序适配器(继承IComarable接口),然后在其compare方法中对两个对象进行比较.

    稳定部分:
        interface Istack  // 客户期望的接口,这里被适配的对象是一个ArrayList对象
        {
            
    public void Push(object item);
            
    public object Pop();
            
    public object Peek();
        }

    变化部分:

     //对象适配器(推荐使用)
        class AdapterA: Istack //适配对象
        {
            ArrayList adpatee; 
    //被适配的对象

            
    public AdapterA()
            
    {
                
            }


            
    public void Push(object item)
            
    {
                adpatee.Add(item);
            }


            
    public object Pop()
            
    {
                
    return adpatee.RemoveAt(adpatee.Count - 1);
            }


            
    public object Peek()
            
    {
                
    return adpatee[adpatee.Count - 1];
            }

        }


        
    //类适配器
        class AdapterB: ArrayList,Istack //适配对象
        {
            
    public AdapterB()
            
    {
            
            }


            
    public void Push(object item)
            
    {
                
    this.Add(item);
            }


            
    public object Pop()
            
    {
                
    return this.RemoveAt(this.Count - 1);
            }


            
    public object Peek()
            
    {
                
    return this[this.Count - 1];
            }

        }

    主程序:
        //对象适配器优于类适配器
            public static void Main()
            
    {
                AdapterA a 
    = new AdapterA();
                a.Pop();
                a.Push(item);
                a.Peek();

                AdapterB b 
    = new AdapterB();
                b.Pop();
                b.Push(item);
                b.Peek();

            }
  • 相关阅读:
    sabaki and leelazero
    apply current folder view to all folders
    string operation in powershell
    wirte function in powershell
    add environment path to powershell
    Module in powershell
    sql prompt
    vmware中鼠标在部分区域不能使用
    调整多个控件的dock的顺序
    行为型模型 策略模式
  • 原文地址:https://www.cnblogs.com/zjbtony/p/711412.html
Copyright © 2011-2022 走看看