Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtkatakura/60c8de78274588a049cabc66a6ffb16b to your computer and use it in GitHub Desktop.
Save gtkatakura/60c8de78274588a049cabc66a6ffb16b to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
// Version C# to: https://gist.github.com/adomokos/989193
public abstract class CarElement : IVisitable<CarElement> { }
public class Wheel : CarElement
{
public string Name { get; }
public Wheel(string name)
{
this.Name = name;
}
}
public class Engine : CarElement { }
public class Body : CarElement { }
public class Car : CarElement
{
public IEnumerable<CarElement> Elements { get; }
public Car()
{
this.Elements = new CarElement[]
{
new Wheel("front left"),
new Wheel("front right"),
new Wheel("back left"),
new Wheel("back right"),
new Body(),
new Engine()
};
}
public void Accept(IVisitor<CarElement> visitor)
{
foreach (var element in this.Elements)
{
element.Accept(visitor);
}
visitor.Visit(this);
}
}
public interface IVisitable<TElement> { }
public static class VisitableMixin
{
public static void Accept<TVisitor, TElement>(this IVisitable<TElement> self, TVisitor visitor)
where TVisitor : IVisitor<TElement>
where TElement : class
{
visitor.Visit(self as TElement);
}
}
public interface IVisitor<TElement>
where TElement : class
{
void Visit(TElement element);
}
public class CarElementPrintVisitor : IVisitor<CarElement>
{
public void Visit(CarElement element)
{
Console.WriteLine(element.GetType().Name);
}
}
public class CarElementDoVisitor : IVisitor<CarElement>
{
public void Visit(CarElement element)
{
Console.WriteLine($"Do some other visitation: {element.GetType().Name}");
}
}
class Program
{
static void Main(string[] args)
{
var c = new Car();
c.Accept(new CarElementPrintVisitor());
c.Accept(new CarElementDoVisitor());
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment