すらいむがあらわれた

こまんど >  たたかう  にげる

Subwayのサンドイッチ

ここのところずっと仕事のコードのifやforの分岐を追っていて頭がぐるぐるしてました。
そのせいかお昼にSubwayに行ったらこんな発想が頭から離れなくなった。

サブウェイの店員さんの頭の中では動的にif文が組み立てられていそう。notピーマン、notオリーブ、トマト++
http://twitter.com/hayashih/status/1635791461

コードにしてみた。
■Main.cs


using System;

namespace Hayashih.Subway
{
class MainClass
{
static Crew subwayCrew = new Crew();

public static void Main(string[] args)
{
// defaut
subwayCrew.ReceiveSandwichOrder();
Sandwich sandwich1 = subwayCrew.FinishOrder();

Console.WriteLine("sandwich1: " + sandwich1.ToString());

// add tomato,lettuce, pull out pickles, olive
subwayCrew.ReceiveSandwichOrder();
subwayCrew.AddVegetable(Vegetable.Tomato);
subwayCrew.AddVegetable(Vegetable.Lettuce);
subwayCrew.DeleleteVegetable(Vegetable.Pickles);
subwayCrew.DeleleteVegetable(Vegetable.Olive);
Sandwich sandwich2 = subwayCrew.FinishOrder();

Console.WriteLine("sandwich2: " + sandwich2.ToString());

// my favorite :)
subwayCrew.ReceiveSandwichOrder();
subwayCrew.AddVegetable(Vegetable.Olive);
subwayCrew.AddVegetable(Vegetable.Onion);
Sandwich myFavoriteSandwich = subwayCrew.FinishOrder();

Console.WriteLine("myFavoriteSandwich: " + myFavoriteSandwich.ToString());

}
}
}

Subway.cs

using System;
using System.Collections.Generic;

namespace Hayashih.Subway
{
///


/// Subway Crew
///

public class Crew
{

public Crew(){}

private Sandwich currnetSandwich = null;

public void ReceiveSandwichOrder()
{
if( this.currnetSandwich != null ){
this.currnetSandwich = null;
}
this.currnetSandwich = new Sandwich();
}

public void AddVegetable(Vegetable vege)
{
// accepts even if said suddenly.
if( this.currnetSandwich == null )
{
this.currnetSandwich = new Sandwich();
}

this.currnetSandwich.AddVegetable(vege);
}

public void DeleleteVegetable(Vegetable vege)
{
// accepts even if said suddenly.
if( this.currnetSandwich == null )
{
this.currnetSandwich = new Sandwich();
}

this.currnetSandwich.DeleteVegetable(vege);
}

public Sandwich FinishOrder()
{
return this.currnetSandwich;
}

}

///
/// A Sandwich. It is only VEGGIE DELITE!
///

public class Sandwich
{
public Sandwich()
{
this.Ready();
}

private List vegetables = new List();

public void Ready()
{
this.vegetables.Add(Vegetable.Lettuce);
this.vegetables.Add(Vegetable.Olive);
this.vegetables.Add(Vegetable.Onion);
this.vegetables.Add(Vegetable.Pickles);
this.vegetables.Add(Vegetable.Pimiento);
this.vegetables.Add(Vegetable.Tomato);

}

public void AddVegetable(Vegetable vege)
{
this.vegetables.Add(vege);
}

public void DeleteVegetable(Vegetable vege)
{
this.vegetables.Remove(vege);
}

public override string ToString ()
{
string ret = String.Empty;

foreach( Vegetable v in this.vegetables)
{
ret += v.ToString() + " ";
}

return ret;

}

}

public enum Vegetable
{
Tomato,
Olive,
Onion,
Pimiento,
Lettuce,
Pickles
}
}

注)このコードは、店員は1度に1個のサンドイッチしか作れないし(いつも行く店の店員さんはお昼時は1度に2、3個作ります)、客がサンドイッチにアクセスできるし、問題ありありの店ですw


たまにはこんなくだらんことでも考えてクラスの作り方などなどちゃんと思い出して頭の整理をするのもいいかもしれない。