{C#}设计模式辨析.适配器

2021-08-06  本文已影响0人  码农猫爸

背景

示例

using static System.Console;

namespace DesignPattern_Adapter
{
    // 旧类,如网线连接器
    public class NetworkConnector
    {
        public void Connect()
            => WriteLine("The network is available.");
    }

    // 新接口,如使用USB
    public interface IUsb
    {
        void Use();
    }

    // 新类,如网线转USB
    public class UsbAdapter : IUsb
    {
        private readonly NetworkConnector network;

        public UsbAdapter(NetworkConnector network)
        {
            this.network = network;
        }

        public void Use() => network.Connect();
    }

    class Program
    {
        static void Main(string[] args)
        {
            var network = new NetworkConnector();
            var adapter = new UsbAdapter(network);
            adapter.Use();

            ReadKey();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读