惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
Y
Y Combinator Blog
月光博客
月光博客
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
美团技术团队
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
博客园 - 司徒正美
V
Visual Studio Blog
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
The Cloudflare Blog

博客园 - Tristan(GuoZhijian)

Core Design Patterns(16) Chain of Responsibility 职责链模式 Core Design Patterns(15) Template Method 模版方法模式 Core Design Patterns(14) State 状态模式 Core Design Patterns(13) Strategy 策略模式 Core Design Patterns(12) Builder 建造者模式 Core Design Patterns(11) Abstract Factory 抽象工厂模式 Core Design Patterns(10) Singleton 单例模式 Core Design Patterns(9) Factory Method 工厂方法模式 Core Design Patterns(8) Prototype 原型模式 Core Design Patterns(7) Facade 外观模式 Core Design Patterns(5) Flyweight 享元模式 Core Design Patterns(4) Composite 组合模式 Core Design Patterns(3) Bridge 桥接模式 Core Design Patterns(2) Proxy 代理模式 Core Design Patterns(1) Decorator 装饰模式 老调重弹:插件式框架开发的一个简单应用 Behavior模型应用:可拖动的div容器 Microsoft Asp.Net Ajax框架入门(13) PageRequestManager Microsoft Asp.Net Ajax框架入门(12) 了解异步通信层
Core Design Patterns(6) Adapter 适配器模式
Tristan(GuoZhijian) · 2008-03-09 · via 博客园 - Tristan(GuoZhijian)

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. 思考

应用中描述的是最普通的适配器模式的应用
继续扩展,可以有双向适配器、可插入式适配器等。