Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created April 2, 2012 08:13
Show Gist options
  • Save masaru-b-cl/2281555 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/2281555 to your computer and use it in GitHub Desktop.
Visitorパターンの勉強用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
interface IVisitor
{
void Visit(IAcceptor acceptor);
}
interface IAcceptor
{
void Accept(IVisitor visitor);
int Value { get; set; }
IAcceptor Child { get; set; }
}
class Visitor : IVisitor
{
public void Visit(IAcceptor acceptor)
{
var value = acceptor.Value;
Console.WriteLine(
value % 3 == 0 && value % 5 == 0
? "FizzBuzz"
: value % 3 == 0
? "Fizz"
: value % 5 == 0
? "Buzz"
: value.ToString()
);
if (acceptor.Child != null)
{
acceptor.Child.Accept(this);
}
}
}
class Acceptor : IAcceptor
{
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
public int Value { get; set; }
public IAcceptor Child { get; set; }
}
class Program
{
static void Main(string[] args)
{
var acceptors = Enumerable.Range(1, 20)
.Select(x => new Acceptor { Value = x }).ToArray();
var source = acceptors.Zip(acceptors.Skip(1), (x, y) => new {Current = x, Next = y});
foreach (var item in source)
{
item.Current.Child = item.Next;
}
var root = source.First().Current;
root.Accept(new Visitor());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment