'Force method call in all derived classes [duplicate]
I have base and derived classes:
public abstract class DataServiceBase {
public abstract List<Data> GetData(String name);
}
public class DataService : DataServiceBase {
public override List<Data> GetData(String name) {
// GetData from API
// Call Interceptor.Register(List<Data> data)
return data;
}
}
I would like the derived classes to call Interceptor.Register(List<Data> data) in GetData before returning the data.
Is there a way to make sure that this always happens?
Solution 1:[1]
Yes, the template method pattern, as Alexander suggested.
Here, we implement GetData in the abstract base class, which calls the GetDataInternal (for a lack of a better name) hook. The hook is implemented in each derived class and is called when you call GetData (which also calls your interception code).
public abstract class DataServiceBase
{
public List<Data> GetData(String name)
{
var data = GetDataInternal(name);
Interceptor.Register(data);
return data;
}
internal abstract List<Data> GetDataInternal(String name);
}
public class DataService : DataServiceBase
{
internal override List<Data> GetDataInternal(String name)
{
var data = new List<Data>();
// GetData from API
return data;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gerardo Grignoli |
