我写了一个泛型类,大致如下:public class BaseDAL<T> where T : BaseModel, new()
{
int Add(T model){...}
int Update(T model){...}
int Delete(T model){...}
}
然后我想写一个工厂,用来返回
new BaseDAL<News>()
new BaseDAL<Photo>()
...但是这里需要先写一个接口,我不太清楚应该怎么写,是应该写一个让实体类继承的接口IModel,使用BaseDAL<IModel>声明工厂的返回对象,还是写一个IBaseDAL<>,如果这样,尖括号里面写什么?还是两者都需要?
请大家赐教。
{
int Add(T model){...}
int Update(T model){...}
int Delete(T model){...}
}
然后我想写一个工厂,用来返回
new BaseDAL<News>()
new BaseDAL<Photo>()
...但是这里需要先写一个接口,我不太清楚应该怎么写,是应该写一个让实体类继承的接口IModel,使用BaseDAL<IModel>声明工厂的返回对象,还是写一个IBaseDAL<>,如果这样,尖括号里面写什么?还是两者都需要?
请大家赐教。
{
int Add(T model);
int Update(T model);
int Delete(T model);
}让后让泛类BaseDAL实现接口:
public class BaseDAL<T> : IBaseDAL<T> where T : BaseModel, new()工厂也应该是泛方法,返回IBaseDAL:
public IBaseDAL<T> GetDAL<T>() where T : Default2, new()
{
return new BaseDal<T>();
}调用时可通过接口:
IBaseDAL<News> newsDAL = factory.GetDAL<News>();
newDAL.Add(xxx);
从你的描述看不出半点必要。什么是工厂?为什么要写?把时间和精力用在直接new BaseDAL<News>()上有什么不可以?看不出有什么必要写,就不要空洞地消磨时间去写。等你需要了,自然就能在提问时把为什么要工厂解释给我们听。
具体说一下
因为是动态调用,所以声明部分:
IBaseDAL<News> newsDAL这里不能确定是News还是photo,抑或其他。
我主要是这里不知道怎么办。而在工厂方面,我打算是一个方法,通过传进一个category参数,返回相应的实例。
class factory{
public static IBaseDAL<?> GetDAL(string category)
switch(category){
case "news":return new BaseDAL<News>();break;
case "news":return new BaseDAL<Photo>();break;
……
}
}
这里同样的问题,如果动态的话,返回类型是什么,是否需要再写一个IModel类,如果要写,是应该让BaseModel继承还是各个实体类继承,仍不解。
{
int Add();
int Update();
int Delete();
}
News,Photo都实现这个接口:public class NewsDAL : IDAL
{
}public class PhotoDAL : IDAL
{
}
工厂里新建相应类就可以了:class factory
{
public static IDAL GetDAL(string category)
{
switch (category)
{
case "news": return new NewsDAL(); break;
case "photo": return new PhotoDAL(); break;
...... }
}
}
你的方法的确可以。
但是我好不容易把这些DAL们用泛型给抽象了,我不太想为了使用工厂又得把他们拆出来,还有没有其他方法呢?
class factory{
public static IBaseDAL<BaseModel> GetDAL(string category) {
switch(category){
case "news":return new BaseDAL<News>();break;
case "news":return new BaseDAL<Photo>();break;
……
}
}
不过建议你还是改下结构,否则结构比较乱,使用起来也不方便
class factory{
public static IBaseDAL<T> GetDAL<T>(){
if(typeof(T)==typeof(News)){
return (IBaseDAL<T>)new BaseDAL<News>();
}else if (typeof(T)==typeof(Photo)){
return (IBaseDAL<T>)new BaseDAL<Photo>();
}
return null;
}
}
{
public static IBaseDAL<BaseModel> GetDAL(string category)
{
switch (category)
{
case "news": return new BaseDAL<News>(); break;
case "news": return new BaseDAL<Photo>(); break;
}
}
}