複数の入力があって、数値の時と文字の時で処理するクラスを選択したくて、
入力が多くなると無駄なので処理するクラスのnewは一回だけにしたくて、
入力が全部数字だったりするときに文字の方をnewしたくない
そしてインスタンス管理のためのクラスを作りたくなくて、
処理の本筋の流れにごちゃごちゃ書きたくない
という時にクロージャを使った関数で実装してみる
//本筋
public void Main(List<dynamic> args)
{
var func = GetMethod();
args.ForEach(input => func(input).Work(input));
}
//本筋に書きたくない部分
public Func<dynamic,IWorker> GetMethod()
{
IWorker human = null, robot = null;
return (input) =>
{
return input is int
? (human ?? (human = new Human()))
: (robot ?? (robot = new Robot()));
};
}
使ったクラス
public interface IWorker
{
void Work(dynamic value);
}
//数字の時に働く
public class Human : IWorker
{
public Human() => Console.WriteLine("Human new!!");
public void Work(dynamic value) => Console.WriteLine("human " + value);
}
//文字の時に動く
public class Robot : IWorker
{
public Robot() => Console.WriteLine("Robot Created!!");
public void Work(dynamic value) => Console.WriteLine("robot " + value);
}
入力
var values = new List<dynamic> { 1, "1", 2, "test", 3, 4, "5" };
結果
Human new!!
human 1
Robot Created!!
robot 1
human 2
robot test
human 3
human 4
robot 5