学习C#设计模式(八)适配器模式

适配器模式

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

namespace Adapter
{
    //种植接口
    public interface IPlant {
        //种植水果
        void Plant();
    }
    public class Orchard {
        /// <summary>
        /// 在指定城市种植指定水果
        /// </summary>
        /// <param name="city">指定城市名称</param>
        /// <param name="fruit">指定水果名称</param>
        public void Plant(string city, string fruit) {
            Console.WriteLine("{0}果园种植{1}", city, fruit);
        }

    }
    //类适配器 :北京果园
    public class BJOrchard : Orchard, IPlant
    {
        public void Plant()
        {
            //在北京种植苹果
            base.Plant("北京","苹果");
        }
    }
    //类适配器 :上海果园
    public class SHOrchard : Orchard, IPlant
    {
        public void Plant()
        {
            //在北京种植苹果
            base.Plant("上海", "橘子");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //创建北京实例
            IPlant target = new BJOrchard();
            //在北京种植水果
            target.Plant();
            //创建上海实例
            target = new SHOrchard();
            //在上海种植水果
            target.Plant();

            Console.ReadLine();
        }
    }
}

代码解析:

上述代码实现了适配器模式,代码中首先创建了种植接口 IPlant,该接口提供了新的需求种植方法Plant;然后创建了Orchard类,该类表示已存在的果园类,具有Plant方法,适配器类使Orchard类的Write方法适应IPlant接口的Plant方法;接着创建了类适配器BJOrchard,该类实现了IPlant接口并继承了Orchard类,在该类的Plant方法中调用Orchard类的Plant方法,满足了 IPlant 接口的需求。最后还实现了另外一种形式的适配器模式——对象适配器类SHOrchard,该类实现了IPlant接口,在该类中保存了Orchard对象的引用,在Plant方法中调用了Orchard对象的Plant方法,同样满足了IPlant接口的需求。

说明:
适配器模式主要是将类的接口转换成新的接口形式,以满足新的需求。适配器模式应用在对已有类型进行复用但接口与复用需求不一致的场合。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值