本文共 1053 字,大约阅读时间需要 3 分钟。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 适配器模式{ class Program { static void Main(string[] args) { Target target = new Adapter(); target.Request(); Console.ReadKey(); } } ////// 定义客户端期待的接口 /// public class Target { ////// 使用virtual修饰以便子类可以重写 /// public virtual void Request() { Console.WriteLine("这是Target类的Request方法"); } } ////// 定义需要适配的类 /// public class Adaptee { public void SpecificRequest() { Console.WriteLine("这是Adaptee类的SpecificRequest方法"); } } ////// 定义适配器 /// public class Adapter : Target { // 建立一个私有的Adeptee对象 private Adaptee adaptee = new Adaptee(); ////// 通过重写,表面上调用Request()方法,变成了实际调用SpecificRequest() /// public override void Request() { adaptee.SpecificRequest(); } }}
运行:
转载地址:http://gwgr.baihongyu.com/