I have an IComposer interface in my c# project:
public interface IComposer
{
string GenerateSnippet(CodeTree tree);
}
CodeTree is a base class that contains a List<CodeTree> of classes that inherit from CodeTree. For example:
public class VariablesDecleration : CodeTree
{
//Impl
}
public class LoopsDecleration : CodeTree
{
//Impl
}
I can have a few classes that implement IComposer and in each I have the GenerateSnippet that loops over the List<CodeTree> and basically do:
foreach (CodeTree code in tree.Codes)
{
if (code.GetType() == typeof(VariablesDecleration))
{
VariablesDecleration codeVariablesDecleration = (VariablesDecleration) code;
// do class related stuff that has to do with VariablesDecleration
}
else if (code.GetType() == typeof(LoopsDecleration))
{
LoopsDecleration codeLoopsDecleration = (LoopsDecleration) code;
// do class related stuff that has to do with LoopsDecleration
}
}
I have this foreach and if statements repeating in each class that implements IComposer.
I was wondering if there is a better design pattern to handle such a case. lets say tommrow I add a new class that inherits from CodeTree - I would have to go over all the classes that implement IComposer and modify them.
I was thinking about the Visitor Design Pattern - but wasn't sure and not exactly sure if and how to implement it. Does Visitor even the right solution for this case?
Aucun commentaire:
Enregistrer un commentaire