享受代码,享受人生

SOA is an integration solution. SOA is message oriented first.
The Key character of SOA is loosely coupled. SOA is enriched
by creating composite apps.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用Visitor解决水果篮问题

Posted on 2005-06-15 17:13  idior  阅读(2738)  评论(17)    收藏  举报
 

n久没更新blog(忙于考试), 今天看到Allen Lee的一篇随笔忍不住手痒.

具体问题的描述见Allen Lee的随笔.

下面给出我的方案.

1. 需要动态为类添加新的方法.

2. 有一个篮子.(objectstruct)

这两点显然符合了Visitor模式的应用背景.



 

先说一下用法:

如果你要为Apple添加新的行为 XXX.

       public static void Main(string[] args)
        {
            Apple apple = new Apple();
            Orange orange = new Orange();
            Banana banana = new Banana ();
            FruitBasket fb = new FruitBasket();
            fb.Add(apple);
            fb.Add(orange);
            fb.Add(banana);        

            fb.Accept(new XXXVisitor());       

         }

如果要为AppleOrange都添加Core(去核)的功能

fb.Accpet(new CoreVisitor());

所有新的功能无非是添加一个XXXVisitor,并在其中给予具体实现.

上层的结构不需要发生任何变化.

这里主要给出一个解决思路. 有关Visitor模式的介绍请见我以前的随笔.为什么会构造成这样你会从中找到答案.

下面简要给出一些代码:

  1 public abstract class Fruit

    2 {

    3     public void Print()

    4     {

    5     }

    6 

    7     public abstract void Accept(IFruitVisitor fv);

    8 }

    9 

   10 public class Apple : Fruit

   11 {

   12     public override void Accept(IFruitVisitor fv)

   13     {

   14         AppleVisitor av = fv as AppleVisitor; //need cast here

   15 

   16         if (av != null)

   17         {

   18             av.Visit(this);

   19         }

   20     }

   21 }

   22 

   23 public interface AppleVisitor

   24 {

   25     void Visit(Apple apple);

   26 }

   27 

   28 public class XXXVisitor : AppleVisitor, IFruitVisitor//想为谁添加功能就实现谁的visitor接口 

   29 {

   30     public void Visit(Apple n)

   31     {

   32         // TODO:  Add some unique method for apple here

   33     }

   34 

   35     //public void Visit(Orange e)

   36     //{

   37     //   // TODO:  Add some unique method for orange here

   38     //}

   39     //public void Visit(Banana g)

   40     //{

   41     //   // TODO:  Add some unique method for banana here

   42     //}

   43 }

   44 

   45 public class CoreVisitor : AppleVisitor, OrangeVisitor, IFruitVisitor

   46 {

   47    //同时为Apple 和Orange 添加去核的功能
   48     public void Visit(Apple n)

   49     {

   50         // TODO:  Add some core method for apple here

   51     }

   52 

   53     public void Visit(Orange e)

   54     {

   55         // TODO:  Add some core method for orange here

   56     }

   57 

   58     //public void Visit(Banana g)

   59     //{

   60     //   // TODO:  Add some unique method for banana here

   61     //}

   62 }