定义
把类的接口转换成客户端期望的另外的接口。适配器解决因接口的不兼容导致类不能协作的问题。
使用频度:
中高
UML类图
![]()
参与者
该模式参与的类或对象
- 转换Adaptee接口,使其能适应Target接口
C#示例代码
// Adapter pattern -- Structural example
using System;
namespace DoFactory.GangOfFour.Adapter.Structural
{
///
/// MainApp startup class for Structural
/// Adapter Design Pattern.
///
class MainApp
{
///
/// Entry point into console application.
///
static void Main()
{
// Create adapter and place a request
Target target = new Adapter();
target.Request();
// Wait for user
Console.ReadKey();
}
}
///
/// The 'Target' class
///
class Target
{
public virtual void Request()
{
Console.WriteLine("Called Target Request()");
}
}
///
/// The 'Adapter' class
///
class Adapter : Target
{
private Adaptee _adaptee = new Adaptee();
public override void Request()
{
// Possibly do some other work
// and then call SpecificRequest
_adaptee.SpecificRequest();
}
}
///
/// The 'Adaptee' class
///
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
}
|
输出
阅读(872) | 评论(0) | 转发(0) |