开发者

Mixing Repository and Active Record patterns regarding inheritance

开发者 https://www.devze.com 2023-02-14 04:45 出处:网络
What do you think about mixing Repository and Active Record patterns like below? How would you implement the GetAll() method regarding there is an inheritance envolved?

What do you think about mixing Repository and Active Record patterns like below?

How would you implement the GetAll() method regarding there is an inheritance envolved?

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Person(int id)
    {
        this.Id = id;
        new PersonRepository().开发者_运维知识库Load(this);
    }

    public virtual void Save()
    {
        new PersonRepository().Save(this);
    }
}

class Employee : Person
{
    public int RegistrationNumber { get; set; }

    public Employee(int id) : base(id)
    {
        new EmployeeRepository().Load(this);
    }

    public override void Save()
    {
        base.Save();
        new EmployeeRepository().Save(this);
    }
}

interface IRepository<T>
{
    void Save(T x);
    bool Load(T x);
    IEnumerable<T> GetAll();
    // Other methods removed to keep code clean
}

class PersonRepository : IRepository<Person>
{
    public void Save(Person x)
    {
        throw new NotImplementedException();
    }

    public bool Load(Person x)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<Person> GetAll()
    {
        throw new NotImplementedException();
    }
}

class EmployeeRepository : IRepository<Employee>
{
    public void Save(Employee x)
    {
        throw new NotImplementedException();
    }

    public bool Load(Employee x)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<Employee> GetAll()
    {
        // How to return Person data????
        throw new NotImplementedException();
    }
}


If you're worried about incurring the overhead of loading all the Person objects then maybe don't load them until you actually need the data - such as via the Lazy Load approach.

If you needed to populate a list of "People" but didn't want to bring back ALL their data - only the stuff needed for the list (say ID, First and last name) then do only that - maybe using the Person object isn't the right way to go as it's too heavy?

What I tend to do is have a concept in mind (like person) and have two classes that represent them: - A lightweight class designed for lists, etc, typically read-only. - A "full featured" object for when performing operations on a "Person".

Architecturally there's nothing wrong with what you're doing but it's strictly OO based - its not concerned with implications of data retrieval in terms of physical limitations that might be placed on you by the environment the software will actually run in.

basically the approach you have is great but is based on a "per class" approach rather than a set-based one.

0

精彩评论

暂无评论...
验证码 换一张
取 消