如何将方法重构为泛型基类实现?

时间:2015-12-03 10:36:11

标签: c# refactoring abstract-class base-class generic-method

我已经实现了我的Repository类,但我想知道如何将它的方法重构为可以通过不同存储库类型扩展的基类。

我首先创建了下面的基本Repository类,但不确定每个方法应该是多么抽象。另外,我应该如何用通用占位符替换Model类型。

在这个example中,抽象方法只包含方法定义,而不包含实现:

public abstract Array sort(Array arr);

有人可以建议如何重构泛型的方法吗?

我首先创建了基本的抽象Repository类,但是仍然坚持用泛型类型和泛型参数替换方法。

以下示例是Delete(),它特定于CustomerModel。它应该是通用的,以便更容易地重复使用该类:

public abstract class BaseRepository
{
    public async Task DeleteCustomer(CustomerModel customer)
    {
        var collection = StartConnection();
        var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);
        var result = await collection.DeleteOneAsync(filter);
        customers.Remove(customer);
    }
}

因此,例如,这是完整的CustomerRepository类,其中包含远程数据库的CRUD操作。这些方法都特定于CustomerModel,这使得难以重复使用:

public class CustomerRepository : ICustomerRepository
{
    private static List<CustomerModel> customers = new List<CustomerModel>();

    static CustomerRepository()
    {
    }

    private CustomerRepository()
    {

    }

    public static CustomerRepository Instance
    {
        get
        {
            return instance;
        }
    }

    public CustomerModel GetACustomer()
    {
        if (customers == null)
            LoadCustomers();
        return customers.FirstOrDefault();
    }

    public List<CustomerModel> GetCustomers()
    {
        if (customers.Count == 0)
            LoadCustomers();
        return customers;
    }

    public CustomerModel GetCustomerById(ObjectId id)
    {
        if (customers == null)
            LoadCustomers();
        return customers.Where(c => c.Id == id).FirstOrDefault();
    }

    public CustomerModel GetCustomerByEmail(string email)
    {
        if (customers == null)
            LoadCustomers();
        return customers.Where(c => c.Email == email).FirstOrDefault();
    }

    public async Task DeleteCustomer(CustomerModel customer)
    {
        var collection = StartConnection();
        var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);
        var result = await collection.DeleteOneAsync(filter);
        customers.Remove(customer);
    }

    public async Task AddCustomer(CustomerModel customer)
    {
        var collection = StartConnection();
        await collection.InsertOneAsync(customer);
        customers.Add(customer);
    }

    public async Task UpdateCustomer(CustomerModel customer)
    {          
        var collection = StartConnection();
        var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);

        collection.Find(filter).ToString();
        var result = await collection.ReplaceOneAsync(filter, customer, new UpdateOptions { IsUpsert = true });

        var index = customers.FindIndex(a => a.Id == customer.Id);
        customers[index] = customer;
    }

    private void LoadCustomers()
    {
        var collection = StartConnection();

        try
        {
            customers = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
        }
        catch (MongoException ex)
        {
            //Log exception here:
            MessageBox.Show("A connection error occurred: " + ex.Message, "Connection Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
    }

    private static IMongoCollection<CustomerModel> StartConnection()
    {
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("orders");
        //Get a handle on the customers collection:
        var collection = database.GetCollection<CustomerModel>("customers");
        return collection;
    }
}

1 个答案:

答案 0 :(得分:3)

不要创建包含特定于实体的方法的基类。 从头开始制作基础通用。

public class Repository<T> where T : new()
{
    public async Task<T> GetAsync(object key)
    {}

    public async Task DeleteAsync(T t)
    {}
}

添加您想要的任何抽象级别。如果您正在使用例如你的回购中的某种ORM就足够了。

您无法在继承类中更改方法名称。如果所有操作方法都相同,那么使用repos会更直接。

如果您可以按原样使用base,则只会更改Type个参数。所以你要实例化,例如代码中的Repository<Customer>

如果实体之间的逻辑不同,那么例如CustomerRepository : Repository<Customer>并将逻辑放在那里。另外,将base标记为abstract和abstract abstract / virtual。