I am using abstract factory pattern. I need to call an abstract method which is called the HelperClass
.
For example: I have two abstract derived classes. I create ClassA
, then ClassA
calls TakeAction
method. TakeAction
method needs to create another method which uses HelperClass
and callclass the method
SolveProblem`.
Here is my question: How can I call again a ClassA
method in the HelperClass
? Because SolveProblem have some logic and it will be decide to return or not.
class Program {
static void Main(string[] args) {
var classA = new ClassA();
classA.StartOperation();
}
}
public abstract class ClassAbstract {
public abstract void StartOperation();
public void TakeAction() {
var helper = new HelperClass();
helper.SolveProblem(DayOfWeek.Sunday);
}
public abstract void WeekDayOperation();
public abstract void WeekEndOperation();
}
public class ClassA : ClassAbstract {
public override void StartOperation() {
TakeAction();
}
public override void WeekDayOperation() {
}
public override void WeekEndOperation() {
throw new NotImplementedException();
}
}
public class ClassB : ClassAbstract {
public override void StartOperation() {
TakeAction();
}
public override void WeekDayOperation() {
}
public override void WeekEndOperation() {
throw new NotImplementedException();
}
}
public class HelperClass {
public void SolveProblem(DayOfWeek day) {
//Problem solved. I need to call "CallThisMethod" who called this helper class
//How to I Call
switch(day) {
case DayOfWeek.Sunday:
case DayOfWeek.Saturday:
ClassA.WeekEndOperation();
break;
case DayOfWeek.Friday:
FridayOperations();
break;
default:
ClassA.WeekDayOperation();
break;
}
}
public void FridayOperations() {
}
}
One solution would be to pass an instance of type: ClassAbstract
as parameter into the method SolveProblem
. You can use this variable then to call the method.
public void SolveProblem(DayOfWeek day, ClassAbstract c)
{
//Problem solved. I need to call "CallThisMethod" who called this helper class
//How to I Call
switch (day)
{
case DayOfWeek.Sunday:
case DayOfWeek.Saturday:
c.WeekEndOperation();
break;
case DayOfWeek.Friday:
FridayOperations();
break;
default:
c.WeekDayOperation();
break;
}
}
To close the circle you need to pass the current instnace (this
) when calling this method in the base implementation of TakeAction
in the ClassAbstract
:
public abstract class ClassAbstract
{
public abstract void StartOperation();
public void TakeAction()
{
var helper = new HelperClass();
helper.SolveProblem(DayOfWeek.Sunday, this);
}
By the phenomenon of polymorphism the correct implementation of the override will be called. In you example from above it will be the overrides of the methods WeekEndOperation
and WeekDayOperation
of the class ClassA