image.png
Adapater 模式
image.png
解析:用于填补“现有的程序”和“所需的程序”之间差异的设计模式。
两种类型:
1.类适配模式(使用继承的适配器)
2.对象适配器模式(使用委托的适配器)
使用继承的示例
image.png
/// <summary>
/// 广告横幅
/// </summary>
public class Banner
{
private readonly string _str; public Banner(string str)
{
_str = str;
} public void ShowWithParen()
{
Console.WriteLine($"({_str})");
} public void ShowWithAster()
{
Console.WriteLine($"*{_str}*");
}
} /// <summary>
/// 打印
/// </summary>
public interface IPrint
{ void PrintWeak(); void PrintStrong();
} /// <summary>
/// 打印的广告横幅
/// </summary>
public class PrintBanner : Banner, IPrint
{
public PrintBanner(string str) : base(str)
{
}
public void PrintWeak()
{
ShowWithParen();
}
public void PrintStrong()
{
ShowWithAster();
}
} internal class Program
{
private static void Main(string[] args)
{
var p = new PrintBanner("hello");
p.PrintWeak();
p.PrintStrong();
Console.Read();
}
}使用委托的示例
image.png
/// <summary>
/// 打印
/// </summary>
public abstract class Print
{ public abstract void PrintWeak(); public abstract void PrintStrong();
} /// <summary>
/// 打印的广告横幅
/// </summary>
public class PrintBanner : Print
{ private readonly Banner _banner; public PrintBanner(Banner banner)
{
_banner = banner;
} public override void PrintWeak()
{
_banner.ShowWithParen();
} public override void PrintStrong()
{
_banner.ShowWithAster();
}
}角色梳理
Target:对象
定义需要的方法。
Client:请求者
该角色负责使用 Target 定义的方法进行具体处理。
Adaptee:被适配
Adater:适配
使用 Adaptee 的方法满足 Target 角色的需求。
类适配器模式的类图(使用继承)
image.png
对象适配器模式的类图(使用委托)
image.png
要点 & 思路
1.不需要改变现有代码可以使现有代码适配于新接口;
2.版本迭代时兼容旧版本;
image.png
相关模式
Bridge 模式
Adapter 模式用于连接接口不同的类,而 Bridge 模式则用于连接类的功能层次结构与实现层次结构。
Decorator 模式
Adapter 模式用于填补不同接口之间的缝隙,而 Decorator 模式则是在不改变接口的前提下增加功能。
作者:oO反骨仔Oo
链接:https://www.jianshu.com/p/e851a5cdb711
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦






