normalian blog

Let's talk about Microsoft Azure, ASP.NET and Java!

Repositoryパターンを使って書き直してみた

NHibernateのページにも載ってるRepositoryパターンを使い、上記の「Singleメソッドの意義」的なものを書き直したみた。メソッド名、クラス名ともに分かりやすくなったんじゃないかと思う。

class Program
{
	public static void Main(string[] args)
	{
		FoodItemAction action = new FoodItemAction();
		action.Add(2,"マフィン",300).Add( new FoodItem(){Id=5,Name="スコーン",Price=500} );
		action.search(0);
		action.search(10);
		action.search(1);
		Console.Write("Press any key to continue . . . ");
		Console.ReadKey(true);
	}	
}

class FoodItemAction
{	
	public void search( long id )
	{
		FoodItemRepository foodItemRepository = new FoodItemRepository();
		FoodItem item = foodItemRepository.Search( id );
		if( item != null )
		{
			Console.WriteLine("id={0}での検索成功",id);
		}else{
			Console.WriteLine("id={0}での検索失敗",id);
		}
	}
	
	public FoodItemAction Add(long id, string name, long price)
	{
		this.Add( new FoodItem(){Id=id,Name=name,Price=price} );
		return this;
	}
	
	public FoodItemAction Add(FoodItem foodItem)
	{
		new FoodItemRepository().Add( foodItem );
		return this;
	}
}

class FoodItem
{
	public long Id{get;set;}
	public string Name{get;set;}
	public long Price{get;set;}
}


interface IItemRepository<T>{
	T Search(long id);
	IItemRepository<T> Add(T item);
	IItemRepository<T> Remove(T item);
}

class FoodItemRepository : IItemRepository<FoodItem>
{
	static private List<FoodItem> foodList = new List<FoodItem>(){
		new FoodItem{ Id=0, Name="まんが肉", Price=1000},
		new FoodItem{ Id=1, Name="ケーキ", Price=1500},
		new FoodItem{ Id=1, Name="ケーキ??", Price=2500}
	};

	public FoodItem Search(long id)
	{
		try{
			return foodList.Single( foodItem => foodItem.Id == id);
		}catch(InvalidOperationException e){
			Console.WriteLine( "ERROR : id={0}, {1}", id, e.Message);
		}
		return null;
	}

	public IItemRepository<FoodItem> Add(FoodItem foodItem){
		foodList.Add(foodItem);
		return this;
	}
	public IItemRepository<FoodItem> Remove(FoodItem foodItem){
		foodList.Remove(foodItem);
		return this;
	}
}