I'm building an application which runs "tasks". All tasks inherrit BaseTask which contains some default logic/functions which should be available for all tasks like Start, Stop, Enable and Disable functions.
The base class also should contain some active property which tells if the task is active as only "active" tasks can be started.
To give an idea about the code:
// As i have no idea how to declare the active param to make it work, i describe this with a comment in my code.
public abstract class BaseJob {
private Status jobStatus;
// some active property defined here which is false by default
public BaseJob() {
jobStatus = active ? Status.initialized : Status.inactive;
}
public void Start() {
if (active) {
Run();
}
}
public void Stop() {
if (jobStatus == Status.running) {
// logic to stop the job
}
}
public void Enable() {
// set "active" to true
jobStatus.initialized
}
public void Disable() {
Stop();
// Set "active" to false
jobStatus = Status.inactive
}
public void Run() {
..
task();
..
jobStatus = Status.running;
}
public abstract void task() { }
}
public class JobA: BaseJob {
public override void task() {
// The logic of the specific job
}
}
Now the questions:
- How to define the active property in the
BaseJobwhich is false by default but in such a way i can "override" its default value in a child class. Take into account:- That I want to change the active value with the
BaseJobfunctionsEnableandDisable - That I want to guarantee that the
activepropert can only be changed by using the relatedBaseJobfunctions as they may contain more logic than just toggle the "active" bool.
- That I want to change the active value with the
I already tried different ways but in eighter case i run into another issue.
private bool activein the BaseJob does not work as its not accessible and overrideable (is this a correct work? :'-D ) from the child class.- Using an abstract getter/setter cannot do the job as it cannot contain a default value in the BaseJob class
- protected getter and setter or bool is not working as i have no idea how to override the default value from the child class.
protected virual bool activein theBaseJobis not working. `The modifier "virtual" is not valid for this item" is the error i receive.
Possible solution i see: Probably i need to override the constructor which sets the default value isn't it? I actually want to avoid this but i think this is the only option?
I think you can just define a protected virtual property to represent the initial active state. The active field is private so that only the base class has the possibility changing it.
Child classes can override the property to change the default state without touching the private active field.