Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# adapter

作者:风皇霸陵   发布日期:2025-12-07   浏览:111

// 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();
        }
    }
}

解释说明:

  1. Target 接口:定义客户端使用的接口。在这个例子中,ITarget 接口有一个 Request 方法。
  2. Adaptee 类:需要适配的类,它有一个 SpecificRequest 方法,但该方法不符合客户端期望的接口。
  3. Adapter 类:实现了 ITarget 接口,并持有 Adaptee 的实例。它将 Adaptee 的方法转换为 ITarget 接口的方法。
  4. Client 类:使用 ITarget 接口与 Adapter 或其他实现 ITarget 接口的类进行交互。
  5. Program 类:创建 AdapteeAdapter 实例,并通过 Client 类调用 Request 方法。

这个示例展示了如何使用适配器模式将一个现有类的接口转换为客户期望的另一个接口。

上一篇:c# 定义常量

下一篇:c# linq select

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站