I'm implementing the template method pattern and in my abstract class I have a method(TemplateMethod
) that gets some values and passes them to Step2
method.
The conflict I have is that my two concrete implementations use just a partial set of these parameters so I don't like the idea of passing all parameters and I wouldn't want to modify this method signature if another concrete implementation would require different parameters.
I have read about Parameter Object pattern and saw another very similar question in SO but I'm still not convinced. Any suggestions?
Here is my simplified code:
void Main()
{
var concreteClassA = new ConcreteClassA();
concreteClassA.TemplateMethod();
var concreteClassB = new ConcreteClassB();
concreteClassB.TemplateMethod();
}
public abstract class AbstractClass
{
IEngine1 _engine1;
IEngine2 _engine2;
public void TemplateMethod() {
Step1();
//Get some values
var id = _engine1.GetId();
var name = _engine1.GetName();
var anotherId = _engine2.GetAnotherId();
var description = _engine2.GetDescription();
//Pass all values to step 2
Step2(id, name, anotherId, description);
}
public virtual void Step1() { }
public virtual void Step2(int id, string name, int anotherId, int description) {}
}
public interface IEngine1 {
int GetId();
string GetName();
}
public interface IEngine2
{
int GetAnotherId();
int GetDescription();
}
public class ConcreteClassA : AbstractClass
{
public override void Step2(int id, string name, int anotherId, int description)
{
//This class only needs Id and name!
var entity = new Entity {
Id = id,
Name = name
}
DoSomethingWithEntity(entity);
}
private void DoSomethingWithEntity(Entity entity) {
//Logic here
}
}
public class ConcreteClassB : AbstractClass
{
public override void Step2(int id, string name, int anotherId, int description)
{
//This one needs other parameters
var entity = new Entity
{
AnotherId = anotherId,
Name = name,
Description = description
}
DoSomethingElseWithEntity(entity);
}
private void DoSomethingElseWithEntity(Entity entity)
{
//Logic here
}
}
public class Entity {
public int Id { get; set; }
public string Name { get; set; }
public int AnotherId { get; set; }
public int Description { get; set;}
}
Aucun commentaire:
Enregistrer un commentaire