下面的範例使用將學生的成績利用兩個演算法做排序 ( BigToSmall , SmallToBig)
使用訪問者模式的好處是
1.針對結構新增演算法時只需要新增class即可
2.參觀者所做的操作都集中在class 裡 trace 較方便
缺點是
1.當需要針對該結構做更改時 會影響到所有演算法 (更改會較困難)
abstract class Visitor { abstract public void Visit(Element element); } class BigToSmallVisitor : Visitor { public override void Visit(Element element) { ScoreSheet sheet = (ScoreSheet)element; sheet.ScoreList.Sort((x, y) => { return -x.Score.CompareTo(y.Score); }); foreach (ScoreData item in sheet.ScoreList) { Console.WriteLine(item.Name + " / " + item.Score); } } } class SmallToBigVisitor : Visitor { public override void Visit(Element element) { ScoreSheet sheet = (ScoreSheet)element; sheet.ScoreList.Sort((x, y) => { return x.Score.CompareTo(y.Score); }); foreach (ScoreData item in sheet.ScoreList) { Console.WriteLine(item.Name + " / " + item.Score); } } } class ScoreData { private int score; private string name; public int Score { get { return score; } set { score = value; } } public string Name { get { return name; } set { name = value; } } public ScoreData(string name, int score) { this.Name = name; this.Score = score; } } abstract class Element { abstract public void Accept(Visitor visitor); } class ScoreSheet : Element { public List<ScoreData> ScoreList = new List<ScoreData>(); public void Add(ScoreData data) { ScoreList.Add(data); } public override void Accept(Visitor visitor) { visitor.Visit(this); } } public class VisitorApp { public static void Main(string[] args) { ScoreSheet sheet = new ScoreSheet(); sheet.Add(new ScoreData("John", 100)); sheet.Add(new ScoreData("Marry", 90)); sheet.Add(new ScoreData("Ted", 60)); sheet.Add(new ScoreData("Bob", 70)); BigToSmallVisitor bigtosmall = new BigToSmallVisitor(); SmallToBigVisitor smalltobig = new SmallToBigVisitor(); Console.WriteLine("================="); sheet.Accept(bigtosmall); Console.WriteLine("================="); sheet.Accept(smalltobig); Console.ReadKey(); } }Result:
=================
John / 100
Marry / 90
Bob / 70
Ted / 60
=================
Ted / 60
Bob / 70
Marry / 90
John / 100
沒有留言:
張貼留言