logo
down
shadow

Visitor pattern: Number arithmetics based on input


Visitor pattern: Number arithmetics based on input

By : Frank Zara
Date : October 20 2020, 08:10 AM
it fixes the issue Instead the int Evaluate() I created void Accept(IExpressionVisitor visitor) function. The PlusExpression class looked like this now:
code :
sealed class PlusExpression : BinaryExpression
{
    public override void Accept(IExpressionVisitor visitor)
    {
        visitor.Visit(this);
    }
}
class ExpressionIntVisitor : IExpressionVisitor
{
    Stack<int> stack = new Stack<int>();

    public int GetRetVal()
    {
        return stack.Peek();
    }

    public void Visit(LiteralExpression exp)
    {
        stack.Push(exp.Value);
    }

    public void Visit(PlusExpression exp)
    {
        exp.Op0.Accept(this);
        exp.Op1.Accept(this);
        int b = stack.Pop();
        int a = stack.Pop();

        stack.Push(checked(a + b));
    }


Share : facebook icon twitter icon
Benefits of accumulating state during traversal of an object structure by a visitor in a visitor pattern and how can the

Benefits of accumulating state during traversal of an object structure by a visitor in a visitor pattern and how can the


By : Ali Shams
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You can add fields to the visitor class and store state there.
Example:
code :
class MyVisitor implements Visitor {

  private final List<Object> seenObjects = new ArrayList<Object>();

  void visitFoo(Foo f) {
    seenObjects.add(f);
  }

  void visitBar(Bar b) {
    seenObjects.add(b);
  }
}
class MyHandler {

  static void handle(Object o, List<Object> seenObjects) {
    seenObjects.add(o);
    if (o instanceof Foo) {
      // ...
    } else if (o instanceof Bar) {
      // ...
    }
    // possibly a recursive call to handle() somewhere, passing the seenObjects list
  }
}
Visitor Pattern: Should the visitor or the visited object decide the visiting order?

Visitor Pattern: Should the visitor or the visited object decide the visiting order?


By : user2814254
Date : March 29 2020, 07:55 AM
I wish this help you I believe there is no "one correct way". Correct way is the way that meets your needs.
A visitor must visit each element of the object structure. The question is, how does it get there? Who is responsible for traversing the object structure? GoF Design Patterns book answers the question as follows:
A Variation on Visitor Pattern: Why not move the 2nd dispatch into the visitor's `Visit` method?

A Variation on Visitor Pattern: Why not move the 2nd dispatch into the visitor's `Visit` method?


By : Müge Arıkut
Date : March 29 2020, 07:55 AM
I wish this helpful for you The main reason the visitor pattern is defined in the GoF book as it is, is that C++ didn't have any form of Run-Time Type Identification (RTTI). They used "double dispatch" to get the target objects to tell them what their type was. A pretty cool, but incredibly hard to describe trick.
The main difference between what you describe and the GoF Visitor pattern (as you mention) is that you have an explicit "dispatch" method - the "visit" method that checks the type of the argument and sends it to the explicit visitFoo, visitBar, etc methods.
Visitor pattern vs downcasting with a limitation on the input type

Visitor pattern vs downcasting with a limitation on the input type


By : Cyrill Jenni
Date : March 29 2020, 07:55 AM
With these it helps The answer clearly depends on what you are trying to achieve here. The visitor pattern is used to work with composed objects like e.g. trees and calls itself on subobjects of that composition. In your example, that would be a text that contains texts and images that contain texts and images... That clearly does not seem to make much sense, so if you are in fact working with texts and images, visitor might not be what you need, and you should provide some more information on what you are trying to achieve.
To your different codes:
Why we need accept() in Visitor pattern and why we cannot call visitor.visit() directly?

Why we need accept() in Visitor pattern and why we cannot call visitor.visit() directly?


By : Sonja Greer
Date : March 29 2020, 07:55 AM
Hope this helps I've been long confused with the Visitor pattern and I've been trying to find explanations all over the Internet and these explanations confused me even more. Now I realised the reasons why Visitor pattern is needed and the way how it is implemented, so here it is:
Visitor pattern in needed to solve the Double Dispatch problem.
code :
void act(Animal& animal, Invoker& invoker)
{
  // Do the job for this specific animal using this specific invoker
}
void act(vector<shared_ptr<Animal>>& animals, vector<shared_ptr<Invoker>>& invokers)
{
    for(auto& animal : animals)
    {
        for(auto& invoker : invokers)
        {
            // Do the job for this specific animal and invoker.
        }
    }
}
#ifndef __VISITOR__
#define __VISITOR__

struct Invoker; // forward declaration;

// -----------------------------------------//

struct Animal
{
    // The name of the function can be anything of course.
    virtual void accept(Invoker& invoker) = 0;
};

struct Fish : public Animal
{
    void accept(Invoker& invoker) override;
};

struct Mammal : public Animal
{
    void accept(Invoker& invoker) override;
};

struct Bird : public Animal
{
    void accept(Invoker& invoker) override;
};

// -----------------------------------------//

struct Invoker
{
  virtual void doTheJob(Fish&   fish)   = 0;
  virtual void doTheJob(Mammal& Mammal) = 0;
  virtual void doTheJob(Bird&   Bird)   = 0;
};

struct MovementInvoker : public Invoker
{
  void doTheJob(Fish&   fish)   override;
  void doTheJob(Mammal& Mammal) override;
  void doTheJob(Bird&   Bird)   override;
};

struct VoiceInvoker : public Invoker
{
  void doTheJob(Fish&   fish)   override;
  void doTheJob(Mammal& Mammal) override;
  void doTheJob(Bird&   Bird)   override;
};

struct FeedingInvoker : public Invoker
{
  void doTheJob(Fish&   fish)   override;
  void doTheJob(Mammal& Mammal) override;
  void doTheJob(Bird&   Bird)   override;
};

#endif
#include <iostream>
#include <memory>
#include <vector>
#include "visitor.h"
using namespace std;

// -----------------------------------------//

void Fish::accept(Invoker& invoker)
{
    invoker.doTheJob(*this);
}

void Mammal::accept(Invoker& invoker)
{
    invoker.doTheJob(*this);
}

void Bird::accept(Invoker& invoker)
{
    invoker.doTheJob(*this);
}

// -----------------------------------------//

void MovementInvoker::doTheJob(Fish& fish)
{
    cout << "Make the fish swim" << endl;
}

void MovementInvoker::doTheJob(Mammal& Mammal)
{
    cout << "Make the mammal run" << endl;
}

void MovementInvoker::doTheJob(Bird& Bird)
{
    cout << "Make the bird fly" << endl;
}

// -----------------------------------------//

void VoiceInvoker::doTheJob(Fish& fish)
{
    cout << "Make the fish keep silence" << endl;
}

void VoiceInvoker::doTheJob(Mammal& Mammal)
{
    cout << "Make the mammal howl" << endl;
}

void VoiceInvoker::doTheJob(Bird& Bird)
{
    cout << "Make the bird chirp" << endl;
}

// -----------------------------------------//

void FeedingInvoker::doTheJob(Fish& fish)
{
    cout << "Give the fish some worms" << endl;
}

void FeedingInvoker::doTheJob(Mammal& Mammal)
{
    cout << "Give the mammal some milk" << endl;
}

void FeedingInvoker::doTheJob(Bird& Bird)
{
    cout << "Give the bird some seed" << endl;
}

int main()
{
    vector<shared_ptr<Animal>> animals = { make_shared<Fish>   (),
                                           make_shared<Mammal> (),
                                           make_shared<Bird>   () };

    vector<shared_ptr<Invoker>> invokers = { make_shared<MovementInvoker> (),
                                             make_shared<VoiceInvoker>    (),
                                             make_shared<FeedingInvoker>  () };

    for(auto& animal : animals)
    {
        for(auto& invoker : invokers)
        {
            animal->accept(*invoker);
        }
    }
}
Make the fish swim
Make the fish keep silence
Give the fish some worms
Make the mammal run
Make the mammal howl
Give the mammal some milk
Make the bird fly
Make the bird chirp
Give the bird some seed
Related Posts Related Posts :
  • Headless Firefox in Selenium C#
  • How do I start a .exe with a json string as parameter correctly?
  • StreamContent not loaded to the end
  • HAP parses formatting in HTML documents
  • repeat and count a loop in an unordered sequence in C#
  • Redundant Casting in Visual studio
  • Lost references in Visual Studio 2017 solution
  • Is there a way to add two numbers using a private constructor in C#
  • Is it possible to execute multiple SSH commands from a single login session with SSH.NET?
  • How can I get NHibernate to map to a Tuple or Class?
  • MVC 5 C# Window Authentication pop up when I navigate to a certain area
  • Mongo C# driver toJson() DateTime
  • Coprime integers
  • What is the purpose with files ending with *CS.cs in Xamarin Forms projects?
  • MVC5 / Entity | Update/Create Complex Model
  • How to return auto increment ID from SQL using Petapoco ORM in .NET MVC
  • Create new web app offline c# using Visual Studio
  • How many times is ordered the IEnumerable in this case?
  • C# error when update database 2008 to sql 2016
  • How to insert string in multiple continuous pattern in windows c#
  • How to send temp data from Partial View to its parent View
  • C# encapsulation when getting updates from asynchronous method
  • Asp net core Content Security Policy implementation
  • @Html.DropDownList() Placeholder as Disable and Selected
  • Set AM/PM in Material Time Picker WPF
  • Ninject passing reference in constructor
  • C# Entity Framework text SQL query wrapper
  • Core 2.0 MVC - AD Group Authorization for logging
  • Decentralized NLog Target per Http request
  • How to use x:Object and when?
  • Displays file icons in asp.net on GridView
  • How do I avoid two (or more) threads that work on a table at the same time to not work on same row?
  • Add xml attribute for property in DB First
  • How do i execute 2 sql queries by clicking a button [C#]
  • convert jsonstring to objects c#
  • How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
  • How to run a .NET Core console application on Linux
  • UI not updating for bound element
  • C# Odata v4 open type raw values
  • DocumentFormat.OpenXml Modify Creator Propery of Document
  • How to SetBasePath in ConfigurationBuilder in Core 2.0
  • ASP MVC5 public readonly variable changes value when it should not
  • How to conditionally select item from hashset with queryable linq?
  • Progress Bar C# not showing the real progress
  • Correct logic to reconnect in SignalR with HubConnection
  • ComboBox with two or more sections
  • .NET listbox to SQLite DB
  • C# Ninject binding from Dictionary<Type, Type>
  • asp.net mvc -view displaying real-time progress status
  • Getting reference to dependent in service with generic type
  • Implementing EqualityCompare vs overriding GetHashCode and Equals
  • C# Linq Find all indexes of item in List<int> within another List<int>
  • XML image how to display at data grid columns in c#.net
  • How to override Equals and GetHash of HashSet
  • Creating Windows authentication and SQL Server authentication in login form
  • How to interop with Azure Service Bus topics created by MassTransit using Rebus?
  • MVC 5 Google Calendar Integration
  • C# - Use parallel arrays to calculate cost of a phone call in GUI
  • Use a int in entire code
  • How to display newly added element at the top of StackPanel in WPF?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org