意图:
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

photo


Target
定义一个目标接口,可以是一个接口也可以是一个抽象类.
Adapter
适配器类,它要实现目标接口且维护一个被适配对象的实例.
Adaptee
被适配对象
Client
客户端调用
很典型的例子就是笔记本电脑的电源适配器,它通过适配器将直流电转化为笔记本电脑所需的标准电压.

class Program
    {
        static void Main(string[] args)
        {
            ITarget t = new Adapter(new Adaptee());
            t.WriteEvent(DateTime.Now.ToString());
            Console.Read();
        }
    }

    /// <summary>
    /// 目标接口
    /// </summary>
    interface ITarget
    {
        void WriteEvent(string msg);
    }

    /// <summary>
    /// 适配器类,它要实现目标接口且维护一个被适配对象的实例
    /// </summary>
    class Adapter : ITarget
    {
        Adaptee adaptee;
        public Adapter(Adaptee a)
        {
            adaptee = a;
        }
        /// <summary>
        /// 实现目标接口的方法,将它委托给被适配对象去执行,而这一切对客户来说是解耦的
        /// </summary>
        /// <param name="msg"></param>
        public void WriteEvent(string msg)
        {
            adaptee.AdapteeWrite(msg);
        }

    }


    /// <summary>
    /// 被适配对象
    /// </summary>
    class Adaptee
    {
        public void AdapteeWrite(string msg)
        {
            Console.WriteLine("这里适配器在起作用:"+msg);
        }
    }


适配器模式又分为对象适配与类适配,对象适配通过组合实现,如上面的例子.类适配通过继承来实现.

输出结果

photo

相关文章

2 Responses

  1. 彩虹之旅 五月 28 2008 , 00:52 cn
    彩虹之旅
    先来学习一下,最近准备开始多看看.NET方面的学习书了,到时候还希望能多向 幻想曲你请教一下的!wink
    #1
  2. 幻想曲 五月 28 2008 , 00:54 cn
    幻想曲
    嗯哈
    共同学习
    #2

Write a comment:



(将显示你的Gravatar图标)  



[b][/b] - [i][/i] - [u][/u]- [quote][/quote]

:-/ ^_^ :d :o :kiss: :) :p :se: [yeah] :( :love: :han: :up: :cry: :zzz: o_o

暂时停止交换链接.

评论提交有问题?