「男人成功時,背後多半有一個偉大的女人。設計模式
女人成功時,背後大多有一個不成功的男人。ide
男人失敗時,悶頭喝酒,誰也不用勸。this
女人失敗時,眼淚汪汪,誰也勸不了。spa
男人戀愛時,凡事不懂也要裝懂。設計
女人戀愛時,遇事懂也裝做不懂。」code
根據上面這段話,可變成如下代碼:blog
/// <summary> /// 人員 /// </summary> public abstract class Person { //獲得結論或反應 public abstract void GetConclusion(Action action); } /// <summary> /// 男人 /// </summary> public class Man : Person { public override void GetConclusion(Action action) { action.ManConclusion(this); } } /// <summary> /// 女人 /// </summary> public class Woman : Person { public override void GetConclusion(Action action) { action.WomanConclusion(this); } }
/// <summary> /// 表現 /// </summary> public interface Action { void ManConclusion(Man man); void WomanConclusion(Woman woman); } /// <summary> /// 成功 /// </summary> public class Success : Action { public void ManConclusion(Man man) { Console.WriteLine("{0},{1}時,背後多半有一個偉大的女人。", man.GetType().Name, this.GetType().Name); } public void WomanConclusion(Woman woman) { Console.WriteLine("{0},{1}時,背後大多有一個不成功的男人。", woman.GetType().Name, this.GetType().Name); } } /// <summary> /// 失敗 /// </summary> public class Failing : Action { public void ManConclusion(Man man) { Console.WriteLine("{0},{1}時,悶頭喝酒,誰也不用勸。", man.GetType().Name, this.GetType().Name); } public void WomanConclusion(Woman woman) { Console.WriteLine("{0},{1}時,眼淚汪汪,誰也勸不了。", woman.GetType().Name, this.GetType().Name); } } /// <summary> /// 戀愛 /// </summary> public class Amativeness : Action { public void ManConclusion(Man man) { Console.WriteLine("{0},{1}時,凡事不懂也要裝懂。", man.GetType().Name, this.GetType().Name); } public void WomanConclusion(Woman woman) { Console.WriteLine("{0},{1}時,遇事懂也裝做不懂。", woman.GetType().Name, this.GetType().Name); } }
class Program { static void Main(string[] args) { Action action = new Success(); new Man().GetConclusion(action); new Woman().GetConclusion(action); Action action1 = new Failing(); new Man().GetConclusion(action1); new Woman().GetConclusion(action1); Action action2 = new Amativeness(); new Man().GetConclusion(action2); new Woman().GetConclusion(action2); } }
運行結果:string
訪問者模式是傾向性拓展設計,在該例子中,表現形式容易拓展,可是人員類型不容易拓展。it
注:《大話設計模式》-訪問者模式io