Witam, dzisiaj przy tworzeniu pewnego systemu zorientowałem się iż zataczam koło i musi istnieć lepsze rozwiązanie. Mianowicie mam 4 kontrolery, które posiadają część wspólnych metod.
Każdy kontroler musi m.in oczekuje metody, która będzie mu zwracała liste obiektów danego typu. Problemem jest okropna redundancja mojego kodu. Nie potrafie zaimplementować odpowiedniego wzorca, tak by za to wszystko odpowiadała jedna metoda.
Kod nie jest skomplikowany, więc myśle, że nie musze więcej wyjaśniać.
public class FolderManageController
{
public ActionResult GetDetails()
{
return View();
}
public ActionResult Add()
{
return View();
}
public ActionResult Get()
{
new Folder().Get(10);
return View();
}
}
public class ProductManageController
{
public ActionResult GetDetails()
{
return View();
}
public ActionResult Add()
{
return View();
}
public ActionResult Get()
{
new Product().Get(10);
return View();
}
}
public class UserManageController
{
public ActionResult GetDetails()
{
return View();
}
public ActionResult Add()
{
return View();
}
public ActionResult Get()
{
new User().Get(10);
return View();
}
}
interface IQuery
{
object Get();
object Get(int counter);
object GetDetails();
void Add();
}
class User : IQuery
{
public void Add()
{
throw new NotImplementedException();
}
public object Get()
{
return _GetRecords(0);
}
public object Get(int counter)
{
return _GetRecords(counter);
}
public object GetDetails()
{
throw new NotImplementedException();
}
private object _GetRecords(int counter)
{
List<User> list;
using (var databaseContext = new DatabaseContext())
{
if (counter == 0)
{
list = databaseContext.User.ToList();
}
else
{
list = databaseContext.User.Take(counter).ToList();
}
}
return list;
}
}
class Product : IQuery
{
public void Add()
{
throw new NotImplementedException();
}
public object Get()
{
return _GetRecords(0);
}
public object Get(int counter)
{
return _GetRecords(counter);
}
public object GetDetails()
{
throw new NotImplementedException();
}
private object _GetRecords(int counter)
{
List<Product> list;
using (var databaseContext = new DatabaseContext())
{
if (counter == 0)
{
list = databaseContext.Product.ToList();
}
else
{
list = databaseContext.Product.Take(counter).ToList();
}
}
return list;
}
}
class Folder : IQuery
{
public void Add()
{
throw new NotImplementedException();
}
public object Get()
{
return _GetRecords(0);
}
public object Get(int counter)
{
return _GetRecords(counter);
}
public object GetDetails()
{
throw new NotImplementedException();
}
private object _GetRecords(int counter)
{
List<Folder> list;
using (var databaseContext = new DatabaseContext())
{
if (counter == 0)
{
list = databaseContext.Folder.ToList();
}
else
{
list = databaseContext.Folder.Take(counter).ToList();
}
}
return list;
}
}
tempalte
. Do dyskusji na temat opisanego przez Ciebie problemu służą posty, więc proszę ich używaj, gdy odpisujesz na dawane Ci porady.