设计模式 -(7)适配器模式(结构型)


将一个类的接口转换成客户希望的另外一个接口。Adpater模式使得原本由于接口不兼容而不能在一起工作的那些类可以一起工作

目标抽象角色(Target)#

定义客户要用的特定领域接口

适配器(Adapter)#

调用另一个接口,作为一个转换器

适配器(Adaptee)#

定义一个接口,Adapater需要介入

客户端(Client)#

协同对象符合Adapater适配器

插线板案例

两种类型的适配器模式#

  • 类适配器(采用继承的方法)
  • 对象适配器(采用对象组合的方式)




Target
    interface Target
    {
        void MyOutPut();
    } 

Adaptee
    interface Adaptee
    {
        void OutPut();
    } 

ConcreteAdaptee1
    public class ConcreteAdaptee1 : Adaptee
    {
        public void OutPut()
        {
            Console.WriteLine("From ConcreteAdaptee");
        }
    } 
ConcreteAdaptee2
    class ConcreteAdaptee2 : Adaptee
    {
        public void OutPut()
        {
            Console.WriteLine("From ConcreteAdaptee2");
        }
    } 
Adapter
    class Adapter : Target
    {
        private Adaptee _adaptee; //必须要维护一个Adaptee类型的成员变量

        public Adapter(Adaptee adaptee)
        {
            this._adaptee = adaptee;
        }

        public void MyOutPut()
        {
            this._adaptee.OutPut();
        }
    } 
Client

    class Client
    {
        static void Main(string[] args)
        {
            Target target = new Adapter(new ConcreteAdaptee1());
            target.MyOutPut();

            target = new Adapter(new ConcreteAdaptee2());
            target.MyOutPut();

            Console.Read();
        }
    } 


分析





作者:【唐】三三

出处:https://www.cnblogs.com/tangge/p/5900327.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   【唐】三三  阅读(282)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示