有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在存储库模式中必须创建多少存储库接口?

假设我们有以下课程:

public class User
{
    //User Definitions Goes Here
}

public class Product
{
    //Product Definitions Goes Here
}

public class Order
{
    //Order Definitions Goes Here
}

有了以上模型,我是否应该只创建一个存储库,比如:

public interface IRepository
{
    //IRepository Definition Goes Here
}

或者最好有多个存储库:

public interface IUserRepository
{
    //IUserRepository Definition Goes Here
}

public interface IProductRepository
{
    //IProductRepository Definition Goes Here
}

public interface IOrderRepository
{
    //IOrderRepository Definition Goes Here
}

每种方法的优缺点是什么


共 (2) 个答案

  1. # 1 楼答案

    如果你采用第一种方法,你就会避免重复自己,满足枯燥的原则。但是,通过将未连接的项集中在一个接口和任何实现类中,打破了关注点分离原则

    如果你采用第二种方法,你就实现了良好的关注点分离,但可能会重复你自己,从而打破枯燥的原则

    一种解决方案是第三种方法:混合

    public interface IRepository<T>
    {
        IEnumerable<T> Query {get;}
        void Add(TEntity entity);
        void Delete(TEntity entity);
    }
    
    public interface IUserRepository : IRepository<IUser>;
    public interface IProductRepository : IRepository<IProduct>;
    public interface IOrderRepository : IRepository<IOrder>;
    

    然后,这种方法满足这两个原则

  2. # 2 楼答案

    没有必须。你可以创建应用所需的任意数量。您可以为每个业务对象提供一个存储库接口和一个通用接口

    差不多

    interface ICRUDRepo<T> //where T is always a Domain object
    {
        T get(GUid id);
        void Add(T entity);
        void Save(T entity);
     }
    
    //then it's best (for maintainability) to define a specific interface for each case
    
    interface IProductsRepository:ICRUDRepo<Product>
    {
        //additional methods if needed by the domain use cases only
    
        //this search the storage for Products matching a certain criteria,
        // then returns a materialized collection of products 
        //which satisfy the given criteria
        IEnumerable<Product> GetProducts(SelectByDate criteria);
     }
    

    这一切都是关于拥有一个干净清晰的抽象,它将允许域与持久性的适当分离

    通用的抽象就在那里,这样我们就可以省去一些击键,并且也许可以有一些通用的扩展方法。然而,出于这些目的使用通用接口并不算枯燥