●访问者模式
“男人成功时,背后多半有一个伟大的女人。
女人成功时,背后大多有一个不成功的男人。
男人失败时,闷头喝酒,谁也不用劝。
女人失败时,眼泪汪汪,谁也劝不了。
男人恋爱时,凡事不懂也要装懂。
女人恋爱时,遇事懂也装作不懂。”
根据上面这段话,可变成以下代码:
////// 人员 /// public abstract class Person { //得到结论或反应 public abstract void GetConclusion(Action action); } /// /// 男人 /// public class Man : Person { public override void GetConclusion(Action action) { action.ManConclusion(this); } } /// /// 女人 /// public class Woman : Person { public override void GetConclusion(Action action) { action.WomanConclusion(this); } }
////// 表现 /// public interface Action { void ManConclusion(Man man); void WomanConclusion(Woman woman); } /// /// 成功 /// 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); } } /// /// 失败 /// 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); } } /// /// 恋爱 /// 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); } }
运行结果:
访问者模式是倾向性拓展设计,在该例子中,表现形式容易拓展,但是人员类型不容易拓展。
注:《大话设计模式》-访问者模式