MVC and Observer pattern

2019-04-02 16:33发布

问题:

I am having problems with implementing Observer pattern in my project. The project has to be made as MVC in C#, like a Windows application.
In my domain model I have for example Country class and Country repository. I have a Country controller and views for seeing all countries(a list on a form), adding new country, and editing existing country.
I don't know how many views will have to know about changes connected with changing Country. The thing is I have to use Observer pattern. And on the web I can find only examlpes when a Subject is Country and Observer is a form that is editing a country and all the examples are in console application.

I need that all my forms that have lists of countries know about adding new country, not just editing existing ones. How am I supposed to do that, should I make a repository a Subject?

回答1:

You could create a 'ManageCountry' task, which lets you edit / add countries. This task could have an event 'CountryChanged', where other views can subscribe to.

When you modify a country, or create a new country, you raise the event, and subscribers can react to it. You just have to make sure that the event you raise, uses some custom EventArgs so that you can pass the Country object that has modified to the eventhandler.

What are you using to implement an MVC app ? Are you using some kind of framework for it ?



回答2:

In C# (or .NET generally) you can use events and delegates which are special observer/monitor/listener implementations.

I don't know about DDD, but I would add an "NewCountryAdded"-event or "CountryListChanged"-event or something like that.



回答3:

Hmm, to me it sounds that you should make a repository a subject, so that the repository works as a publisher to the forms. Try this and let us know if it worked out.