亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

第 2 章 Adapter 模式 -- 加個“適配器”以便復用

標簽:
設計模式

webp

image.png

Adapater 模式

webp

image.png

解析:用于填补“现有的程序”和“所需的程序”之间差异的设计模式。
两种类型:
1.类适配模式(使用继承的适配器)
2.对象适配器模式(使用委托的适配器)

使用继承的示例

webp

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();
        }
    }

使用委托的示例

webp

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 角色的需求。

类适配器模式的类图(使用继承)

webp

image.png

对象适配器模式的类图(使用委托)

webp

image.png

要点 & 思路

1.不需要改变现有代码可以使现有代码适配于新接口;
2.版本迭代时兼容旧版本;


webp

image.png

相关模式

Bridge 模式

Adapter 模式用于连接接口不同的类,而 Bridge 模式则用于连接类的功能层次结构与实现层次结构。

Decorator 模式

Adapter 模式用于填补不同接口之间的缝隙,而 Decorator 模式则是在不改变接口的前提下增加功能。



作者:oO反骨仔Oo
链接:https://www.jianshu.com/p/e851a5cdb711


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消