适配器模式(Adapter)包含以下主要角色:
适配者Adaptee(已经存在,与接口不兼容的类),他有一个SpecificRequest(特殊请求)方法
- class Adaptee
- {
- public void SpecificRequest()
- {
- Console.WriteLine("Called SpecificRequest()");
- }
- }
我们的目标接口Taget(切口中定义了一个请求方法)
- interface ITarget
- {
- void Request();
- }
适配器Adapter,在Adapter中,实现了我们的接口,但是实际上是调用了Adaptee的SpecificRequest方法
- class Adapter : ITarget
- {
- private readonly Adaptee _adaptee;
-
- public Adapter(Adaptee adaptee)
- {
- _adaptee = adaptee;
- }
-
- public void Request()
- {
- _adaptee.SpecificRequest();
- }
- }
然后!我们就可以通过ITarget接口来使用Adaptee的SpecificRequest方法了
- public static void Main(string[] args)
- {
- ITarget target = new Adapter(new Adaptee());
- target.Request();
- }
优点:
缺点:
使用场景: