首先,我对问题标题的模糊性以及是否已经在其他地方提出过这个问题表示歉意。由于存在大量其他“这种模式叫什么”问题,我很难找到类似的答案。
我有以下抽象类:
public abstract class PositionProvider<T> : DalProvider<T>, IDalProvider
where T : IPositionEntity
{
protected PositionProvider()
: base() { }
public RP_PositionType PositionType
{
get
{
return _positionType;
}
}
private RP_PositionType _positionType;
public abstract List<T> GetList();
internal void SetPositionType(RP_PositionType positionType)
{
if (_positionType == null)
{
_positionType = positionType;
}
else
{
throw new NotSupportedException(
"PositionType can only be set once.");
}
}
}
然后我就得到了这个类的具体实现:
public class SqlPositionProvider<T>
: PositionProvider<T> where T : IPositionEntity
{
public override List<T> GetList()
{
int positionTypeId = (int)this.PositionType;
// Return the matching items here
}
}
然后,许多不同的“项目”类都会使用它,例如以下类,但将 CustomerEntity 替换为 SiteEntity/MajorEntity/MinorEntity:
public class CustomerProvider
{
public static PositionProvider<CustomerEntity> Instance
{
get
{
if (_instance == null)
{
DalHelper.CreateInstance<PositionProvider<CustomerEntity>>(
out _instance);
_instance.SetPositionType(RP_PositionType.Customer);
}
return _instance;
}
}
private static PositionProvider<CustomerEntity> _instance;
}
CustomerProvider、SiteProvider 等Provider 都只是持有PositionProvider 类的特定实例。它们之间的唯一区别是实体类型和 RP_PositionType 枚举。这样我就可以在 GetList() 中使用相同的 Sql 具体实现来根据 PositionType(当枚举转换为 int 值时的 PositionTypeId)从特定表中提取所有记录。
最佳答案
这就是Abstract Factory Pattern 。是的,这是一种有用且广泛使用的设计模式。
关于C# - 这是一个 'good' 数据访问模式吗?它叫什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1630936/