// C# Adapter Pattern Example
using System;
namespace AdapterPatternDemo
{
// Target interface
public interface ITarget
{
void Request();
}
// Adaptee class
public class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Adaptee.SpecificRequest()");
}
}
// Adapter class
public class Adapter : ITarget
{
private Adaptee _adaptee;
public Adapter(Adaptee adaptee)
{
_adaptee = adaptee;
}
public void Request()
{
// Call the adaptee's specific request
_adaptee.SpecificRequest();
}
}
// Client class
public class Client
{
private ITarget _target;
public Client(ITarget target)
{
_target = target;
}
public void Execute()
{
_target.Request();
}
}
class Program
{
static void Main(string[] args)
{
// Create an instance of Adaptee
Adaptee adaptee = new Adaptee();
// Create an adapter to adapt Adaptee to ITarget
ITarget target = new Adapter(adaptee);
// Create a client and pass the target to it
Client client = new Client(target);
// Execute the client's operation
client.Execute();
}
}
}
ITarget 接口有一个 Request 方法。SpecificRequest 方法,但该方法不符合客户端期望的接口。ITarget 接口,并持有 Adaptee 的实例。它将 Adaptee 的方法转换为 ITarget 接口的方法。ITarget 接口与 Adapter 或其他实现 ITarget 接口的类进行交互。Adaptee 和 Adapter 实例,并通过 Client 类调用 Request 方法。这个示例展示了如何使用适配器模式将一个现有类的接口转换为客户期望的另一个接口。
上一篇:c# 定义常量
下一篇:c# linq select
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站