祖国母亲生病了,一场突如其来的新冠病毒让这个古老的中华民族正在经历一场全民参与、没有硝烟、却生离死别的战争。每每看到抖音里的那些感人场景虽然不至于声泪俱下,却也是感慨万千、悲愤不已。大家现在都蛰伏在家,等待时机成熟破茧化蝶。相信这个春节在很多人的记忆里永远再也无法抹去,只希望所有人都安好!岁岁平安!
想起抖音里某位才人拍摄的一段视频,视频里这位仁兄使用女用卫生巾夹在普通一次性口罩中混合使用,以提高过滤功效。感叹一句,此乃神人也,有才,不得不佩服!笑归笑,这里不禁想起了设计模式中一个称之谓适配器(Adapter)的模式,所谓Adapter模式简言之,适配器能够使原本两个不兼容的接口能够协同工作。这位才人他没有将卫生巾直接戴在嘴上、卡在脸上(那可不适配),而是通过一个一次性口罩进行了转换、隐藏、适配,然后交由一次性口罩来担负起对外的形象任务,抽象一点的说其实这也算是一个适配器模式的应用:)
好吧,让我们来正式认识一下Adapter模式吧!
定义:
Adapter模式,允许不兼容的类通过一个适配器转换为客户端所期望的接口来协同工作。
UML:

实例:
using System;
namespace AdapterPattern
{
internal class Program
{
private static void Main(string[] args)
{
//The client needs a target type called Target.
Action<Target> client = (_) => { Console.WriteLine(_.GetName()); };
//An adapter converts an existing type called adaptee to the Target type.
Target target = new Adapter(new Adaptee());
//client is executing.
client(target);
Console.ReadKey();
}
}
/// <summary>
/// This represents a type that the client can accept.
/// </summary>
public interface Target
{
string GetName();
}
/// <summary>
/// It represents an adapter that converts an object that cannot be accepted by the client to the Target type.
/// </summary>
/// <seealso cref="AdapterPattern.Target" />
public class Adapter : Target
{
public Adapter(Adaptee adaptee)
{
Adaptee = adaptee;
}
public Adaptee Adaptee { get; }
public string GetName()
{
return Adaptee.Foobar;
}
}
/// <summary>
/// It represents a type that cannot be accepted by the client.
/// </summary>
public class Adaptee
{
public string Foobar { get; } = "Foobar";
}
}
想比较而言,Adapter模式是一个比较容易理解的模式,其它的我也不多说了,再次希望所有人都平平安安:)
