前言
C#设计模式(6)——适配器模式(Adapter Pattern)
适配器模式主要用于在不修改现有类的情况下,使本来不包含的类可以一起工作。
代码
//插头接口
public interface IPlug
{void Charge();
}
//插头适配
public class Adapter
{public void ConverterCharge(){Console.WriteLine($"{this.GetType().Name}:使用适配插头充电...");}
}//插头类适配
public class PlugClassAdapter : Adapter, IPlug
{public void Charge(){ConverterCharge();}
}//插头对象适配
public class PlugObjectAdpter : IPlug
{private Adapter _adapter;public PlugObjectAdpter(Adapter adapter){this._adapter = adapter;}public void Charge(){_adapter.ConverterCharge();}
}/** 适配器模式:(Adapter Pattern)*/internal class Program{static void Main(string[] args){IPlug plug = new PlugClassAdapter();plug.Charge();// 对象适配器Adapter adaptee = new Adapter();PlugObjectAdpter twoPlug = new PlugObjectAdpter(adaptee);twoPlug.Charge();Console.ReadLine();}}