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