A similar question with almost same title is there but it asks about a different aspect.
My question is should an interface never contain implementation as best OOP practices? But it makes good sense with observer pattern since any observer would readily get the helpful functions that they would need from base class (register, remove, notify). I bet there would be more cases like that too.
So why C# doesn't allow implementation in interfaces? The 8.0 now does but still instance data can't be defined so it's still limited.
Why should the derived classes have to implement these functions when it makes good sense in interface itself and it encapsulate the whole thing?
I also ready this good blog and notes the following:
-
The perfect observer perhaps would be superclass instead of an interface because it can implement the register, remove and notify methods.
-
But this does cause the interface to depend on concrete class (like vector) which I guess would be acceptable compromise.
-
But if this is concrete class, C# doesn't allow multiple interfaces. C++ does allows it but it's not encouraged.
So at the end, an interface perhaps is probably better but it does cause some code duplication that the 'subject' methods have to be implemented in every derived class?
How is the best compromise here and what's the justification for your approach?
This is my subject
class in C++. My question again is why should I not implement these methods in this class and make it interface (which is how has to be in C# and Java)?
class Subject
{
public:
Subject();
~Subject();
virtual void registerObserver(Observer* observer)
{
observers.push_back(observer);
};
virtual void removeObserver(Observer* observer)
{
// find the observer
auto iterator = std::find(observers.begin(), observers.end(), observer);
if (iterator != observers.end()) { // observer found
observers.erase(iterator); // remove the observer
}
}
virtual void notifyObservers()
{
for (Observer* observer : observers) { // notify all observers
observer->update();
}
};
protected:
std::vector<Observer*> observers; // observers
};
Aucun commentaire:
Enregistrer un commentaire