适配器

说到适配器大家都比较熟悉,在现实生活中,家电是两孔的,插座是三孔,怎么把两孔和三孔的匹配上呢,这时候适配器就派上用场了,直接上代码:

两孔的:

public abstract class TwoHole{

  public void SpecificRequest(){

      Console.WriteLine("我是两孔的插座");

  }

}

三孔的:

public interface IThreeHole{

  void Request();

}

适配器:

public class AdapterHole: TwoHole, IThreeHole

{

  public void Request(){

     this.SpecificRequest();

  }

}

 

// 使用适配器

IThreeHole threeHole=new AdapterHole();

threeHole.Request();

 

以上就是适配器模式了,适配器模式有两种,一种是类的适配器(通过继承的方式),另一种是对象适配器(通过包含对象),上面采用的是继承形式的,下面上包含对象适配器模式的代码:

public class ThreeHole
    {
        // 客户端需要的方法
        public virtual void Request()
        {
            // 可以把一般实现放在这里
        }
    }
public class TwoHole{
  
public void SpecificRequest()
        {
            Console.WriteLine("我是两个孔的插头");
        }

}
// 适配器
public class Adapter:ThreeHole{
public TwoHole twoholeAdaptee = new TwoHole();
/// <summary>
        /// 实现三个孔插头接口方法
        /// </summary>
        public override void Request()
        {
            twoholeAdaptee.SpecificRequest();
        }

}

// 使用适配器

IThreeHole threeHole=new AdapterHole();

threeHole.Request();

 

明白了吧,适配器就是这么简单,就是把目标对象包装一下,同时对外提供可访问的接口,本质上还是访问目标对象的方法

posted on 2019-03-20 14:09  1老王  阅读(148)  评论(0编辑  收藏  举报