What is the difference between Strategy pattern and Visitor Pattern?

后端 未结 11 1486
灰色年华
灰色年华 2021-01-29 22:18

I have trouble understanding these two design patterns.

Can you please give me contextual information or an example so I can get a clear idea and be able to map the dif

11条回答
  •  隐瞒了意图╮
    2021-01-29 22:35

    The defining difference is that the Visitor offers a different behavior for subclasses of the element, using operator overloading. It knows the sort of thing it is working upon, or visiting.

    A Strategy, meanwhile, will hold a consistent interface across all its implementations.

    A visitor is used to allow subparts of an object to use a consistent means of doing something. A strategy is used to allow dependency injection of how to do something.

    So this would be a visitor:

    class LightToucher : IToucher{
        string Touch(Head head){return "touched my head";}
        string Touch(Stomach stomach){return "hehehe!";}
    }
    

    with another one of this type

    class HeavyToucher : IToucher{
       string Touch(Head head){return "I'm knocked out!";}
       string Touch(Stomach stomach){return "oooof you bastard!";}
    }
    

    We have a class that can then use this visitor to do its work, and change based upon it:

    class Person{
        IToucher visitor;
        Head head;
        Stomach stomach;
        public Person(IToucher toucher)
        {
              visitor = toucher;
    
              //assume we have head and stomach
        }
    
        public string Touch(bool aboveWaist)
        {
             if(aboveWaist)
             {
                 visitor.Touch(head);
             }
             else
             {
                 visitor.Touch(stomach);
             }
        }
    }
    

    So if we do this var person1 = new Person(new LightToucher()); var person2 = new Person(new HeavyToucher());

            person1.Touch(true); //touched my head
            person2.Touch(true);  //knocked me out!
    

提交回复
热议问题