Core Design Patterns(6) Adapter 适配器模式

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)  阅读(473)  评论(1编辑  收藏  举报