开发者

Call Repositories from centralized class based on event listeners?

I have a program that deals with (virtual) money order transactions, and there are many classes that has logic requiring data to be saved to a database. My question is if I shall call my repositories directly from the various classes, or if I shall instead raise events, which a DatabaseManager class ob开发者_JAVA技巧ject can listen to, and hence all repositories will be called from this one class.

I don't have experience working with databases and repositories, so would appreciate some deeper insight and tips here. Like on what criteria you would chose different approach etc.

It's probably important to note that the database in this case is not used to retrieve data for performing program logic, except on program startup. So it's basically keeping all data in runtime objects, and just dumping to database for archiving.


I would pass an IRepository to my classes which they can then call to save data. For one thing it makes testing easier because you can easily inject a mock repository and on the other hand it makes it explicit that your classes have a dependency like that. You might want to search for the term Dependency Injection.

Simple example:

class Account
{
    public Account(IRepository<Account> repository)
    {
        _Repository = repository;
    }

    public void ChangeOwner(Owner newOwner)
    {
        // change ownership
        _Repository.Save(this);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜