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

推荐订阅源

B
Blog RSS Feed
Jina AI
Jina AI
雷峰网
雷峰网
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
博客园 - 司徒正美
罗磊的独立博客
J
Java Code Geeks
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
Vercel News
Vercel News
A
About on SuperTechFans
I
InfoQ
D
DataBreaches.Net
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
aimingoo的专栏
aimingoo的专栏
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure 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. 思考

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