随笔-42  评论-128  文章-0  trackbacks-4
VS 2008

一个已有的组件(类库)提供的接口与当前客户系统请求的接口不一致时,使用适配器模式,将已有组件的接口转换为客户系统请求的接口。

1. 模式UML图


2. 应用

    目前我们有一套现有的文本日志记录组件,提供了一套供客户端代码请求的接口。
    然而客户端代码请求的却是另外一套接口,为了复用现有的文本日志记录组件,我们使用适配器模式。



TextLogger.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Adapter.BLL {
    
public class TextLogger {

        
public void WriteLog(string message) {
            Console.WriteLine(
"Exception message: {0}", message); 
        }

    }

}


ILogger.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Adapter.BLL {
    
public interface ILogger {

        
void Write(string message);
    }

}


LogAdapter.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Adapter.BLL {
    
public class LogAdapter : ILogger {
        
private TextLogger textLogger = new TextLogger();


        
ILogger Members
    }

}


Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.Adapter.BLL;

namespace DesignPattern.Adapter {
    
class Program {
        
static void Main(string[] args) {

            
string message = "unknown exception occured";
            
new LogAdapter().Write(message);
        }

    }

}


Output



3. 思考

应用中描述的是最普通的适配器模式的应用
继续扩展,可以有双向适配器、可插入式适配器等。
posted on 2008-03-09 15:23 Tristan(GuoZhijian) 阅读(164) 评论(0)  编辑 收藏 所属分类: Design Pattern

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-03-11 16:43 编辑过


相关链接: