CSharp设计模式读书笔记(7):适配器模式(学习难度:★★☆☆☆,使用频率:★★★★☆)...

适配器模式(Adapter Pattern):将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。

模式角色与结构:

对象适配器:

示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharp.DesignPattern.AdapterPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Adaptee adaptee = new Adaptee();
            Target target = new Adapter(adaptee);
            target.Request();

            Console.ReadLine();
        }
    }

    class Adapter : Target
    {
        private Adaptee adaptee;

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

        public void Request()
        {
            adaptee.Operation();
        }
    }

    interface Target
    {
        void Request();
    }

    class Adaptee
    {
        public void Operation()
        { }
    }
}

类适配器:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharp.DesignPattern.AdapterPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Target target = new Adapter();
            target.Request();

            Console.ReadLine();
        }
    }

    class Adapter : Adaptee, Target
    {
        public void Request()
        {
            this.Operation();
        }
    }

    interface Target
    {
        void Request();
    }

    class Adaptee
    {
        public void Operation()
        { }
    }
}

由于Java、C#等语言不支持多重类继承,因此类适配器的使用受到很多限制,例如如果目标抽象类Target不是接口,而是一个类,就无法使用类适配器;此外,如果适配者Adapter为最终(Final)类,也无法使用类适配器。在Java等面向对象编程语言中,大部分情况下我们使用的是对象适配器,类适配器较少使用

双向适配器:

 

 

示例代码:

 

转载于:https://www.cnblogs.com/thlzhf/p/3993334.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值