1.使用组合委托一个黑盒实例对象来实现接口;适配器委托目标类作为构造函数,并委托它来实现接口
2.Code:
class Program { static void Main(string[] args) { IExpectedInterface dependency = new Adapter(new TargetClass()); Console.WriteLine(dependency.MethodA()); Console.ReadLine(); //输出协作类的方法结果 } public interface IExpectedInterface { int MethodA(); } public class Adapter : IExpectedInterface { public Adapter(TargetClass targetClass) { this.target = targetClass; } public int MethodA() { return target.MethodB(); } private TargetClass target; } public class TargetClass { public int MethodB() { return 100; } } }