C# - 这是一个 'good' 数据访问模式吗?它叫什么?

标签 c# design-patterns

首先,我对问题标题的模糊性以及是否已经在其他地方提出过这个问题表示歉意。由于存在大量其他“这种模式叫什么”问题,我很难找到类似的答案。

我有以下抽象类:

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/

相关文章:

model-view-controller - 遵循 MVC 时递归函数放在哪里?

c# - Azure MySql 异常 : The connection string may not be right. 请访问门户以获取引用

c# - 如何在 Unity3D 中使用 GameObject.Find (""找到非事件对象?

c# - 在 javascript 中使警报消息安全的最佳方法

c# - 如何从响应中删除 "method"节点?

unit-testing - 部署一个伪装成程序的大测试

c# - 从 XML 文件中删除特定条目

java - Dao 类的单一职责原则

node.js - 如何处理在我想要的之前返回的异步代码?

ViewController 的快速可重用性