设计模式之双向适配器模式

  • 双向适配器模式:将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
    例子:
    设计和实现一个双向适配器实例,使得猫Cat可以学狗Dog叫Cry() ,狗可以学猫抓老鼠CatchMouse() 。
    类图:
    这里写图片描述
namespace 双向适配器
{
    class Program
    {
        static void Main(string[] args)
        {
            DogTarget dog = new ConcreteDog();
            CatTarget cat = new ConcreteCat();
            dog.Cry();
            cat.CatchMouse();
            Adapter adapter = new Adapter(dog,cat);
            adapter.CatchMouse();
            adapter.Cry();
            Console.ReadKey();
        }
    }
    public interface DogTarget
    {
        void Cry();
    }
    public interface CatTarget
    {
        void CatchMouse();
    }
    public class ConcreteCat : CatTarget
    {

        public void CatchMouse()
        {
            Console.WriteLine("会抓老鼠!");
        } }
  public class ConcreteDog : DogTarget
    {
        public void Cry()
        {
            Console.WriteLine("汪汪汪..");
        }}
    public class Adapter:CatTarget,DogTarget
    {
        private CatTarget cat;
        private DogTarget dog;
        public Adapter(DogTarget dogtarget,CatTarget cattarget)
        {
            this.dog = dogtarget;
            this.cat = cattarget;
        }
        public void Cry()
        {cat.CatchMouse();
        }
        public void CatchMouse()
        {
            dog.Cry();
        }
    }
}

如有错误的地方还请指正!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ExtraMile

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值