背景
- 引入第三方库(dll),满足我方接口
- 我方程序演化后,在不改旧代码的基础上增加新功能
示例
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();
}
}
}
网友评论