设计模式-适配器模式(adapter pattern)

本文详细介绍了适配器模式的概念、动机、适用性、参与者及其类图,并通过示例代码展示了类适配和对象适配的区别和使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

名称: 适配器模式

说说:还记得 xxx 类下面的 xxxWrapper 类吗?

动机:

适用性:

参与者:

结果:将一个类的接口,转换成客户期望的另一个接口

类图(类适配):


类图(对象适配):


说明:感觉对象适配用例要多一点。


demo c#:

namespace adapter {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("类适配:");
            target _t = new adapter_class();    
            _t.speakChinese();
            _t.speakJapanese();
            _t.speakEnglish();

            Console.WriteLine("对象适配:");
            adaptee _a = new adaptee();
            target _t2 = new adapter_object(_a);
            _t2.speakChinese();
            _t2.speakJapanese();
            _t2.speakEnglish();

            Console.Read();
        }
    }

    // main code
    interface target {  // 期望功能
        void speakChinese();
        void speakJapanese();
        void speakEnglish();
    }
    class adaptee {     // 源角色
        public void showChinese() {
            Console.WriteLine("嗯,你说的对!");
        }
        public void showJanpanese() {
            Console.WriteLine("雅蠛蝶~~");
        }
    }

    // 类适配器(继承实现),无需重新实现adaptee,高效
    class adapter_class : adaptee, target {   // 适配器
        public void speakChinese() {
            this.showChinese();
        }
        public void speakJapanese() {
            this.showJanpanese();
        }
        public void speakEnglish() {
            Console.WriteLine("hello world!");
        }
    }

    // 对象适配器(组合实现),更有弹性,没有父类方法被覆盖的隐患
    class adapter_object : target {
        adaptee _adaptee;
        public adapter_object(adaptee a) { 
            this._adaptee = a;
        }
        public void speakChinese() {
            this._adaptee.showChinese();
        }
        public void speakJapanese() {
            this._adaptee.showJanpanese();
        }
        public void speakEnglish() {
            Console.WriteLine("hello world!");
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值