C# 程式設計經典300例 實例102 果園之間互換水果品種 中介者模式
實例102介紹中介者模式,透過第三者類別降低兩個類別之間的耦合度。
實例描述
範例果園之間互換水果品種進行種植,介紹中介這模式。
輸出字串「北京果園種植上海水果」、「上海果園種植北京水果」。
實現過程
//抽象果園類
public abstract class Orchard
{
protected Orchardist orchardist;
public Orchard(Orchardist orchardist)
{
this.orchardist = orchardist;
}
public abstract void PlantRemote();
public abstract void Plant();
}
//北京果園類
public class BJOrchard:Orchard
{
public BJOrchard(Orchardist orchardist):base(orchardist){}
public Orchard(Orchardist orchardist)
{
this.orchardist = orchardist;
}
public override void PlantRemote()
{
this.orchardist.PlantRemote(this);
}
public override void Plant()
{
Console.WriteLine(“種植北京水果”);
}
}
//上海果園類
public class SHOrchard:Orchard
{
public SHOrchard(Orchardist orchardist):base(orchardist){}
public Orchard(Orchardist orchardist)
{
this.orchardist = orchardist;
}
public override void PlantRemote()
{
this.orchardist.PlantRemote(this);
}
public override void Plant()
{
Console.WriteLine(“種植上海水果”);
}
}
//抽象果園類
public abstract class Orchardist
{
public abstract void PlantRemote(Orchard orchard);
}
//北京上海果農
public class BJSHOrchardist :Orchardist
{
Orchard bjOrchard;
Orchard shOrchard;
public Orchard BJOrchard { set { bjOrchard = value}}
public Orchard SHOrchard { set { shOrchard = value}}
public override void PlantRemote(Orchard orchard)
{
if(orchard == this.bjOrchard)
{
Console.Write(“北京果園”);
shOrchard.Plant();
}
else if(orchard == this.shOrchard)
{
Console.Write(“上海果園”);
bjOrchard.Plant();
}
}
}
main函數代碼如下:
BJSHOrchardist orchardist= new BJSHOrchardist();
Orchard bjBJOrchard = new BJOrchard(orchardist);
Orchard shBJOrchard = new SHOrchard(orchardist);
orchardist.BJOrchard = bjBJOrchard;
orchardist.SHOrchard = shBJOrchard;
bjBJOrchard.PlantRemote();
shBJOrchard.PlantRemote();
代碼解析
BJSHOrchardist類別實現BJOrchard與SHOrchard互相調用,但這兩個類別之間不互相引用。
中介者模式主要通過定義一個中介者類來封裝一系列對象的相互調用。中介者類別使得需要互相調用的類別不用互相引用,實現類別之間的鬆耦合,而且中介者類別可以改變類別之間的調用方式。
留言
張貼留言