Composite Pattern, Private methods in both leaf and composite?

161 views Asked by At

I have some trouble figuring out the Composite pattern.

As of right now, i have an interface which includes the methods that should be in both the leaf and composite, for example the void PrintName() method. Is this right? or should the interface include the composite only methods too, like AddChild etc.

In my composite class, the PrintName() method look like this:

public void PrintName(){
Console.WriteLine(_name);
foreach(Child c in List) c.PrintName();
}

And in the leaf class, it is the same just without the forloop.

This seem to be OK, until i needed a private method. Because now, i have to write EXACTLY the same private method in both the leaf and composite classes. This requires me to remember to maintain both if i decide to change/refactor one of them.

I have thought about making the leaf and composite classes inherit this kinds of methods, is this OK? I have also thought about making that kind of method just in the leaf class, and making the composte class make a leaf, which is itself, meaning the composite class always has atleast 1 leaf.

What is best practice regaring the composite pattern?

1

There are 1 answers

0
Dimitris Fousteris On BEST ANSWER

I prefer implementing The add/get/remove methods in Composite class only as the leaf nodes will never implement them. This however has the disadvantage of forcing you to distinguish between leaf and non-leaf nodes, but neither of the two approaches are wrong.

As for the private method duplication you could create a new class implementing the operation you desire with protected access modifier so it won't be visible in the outer world, and have both Composite and leaf nodes inheriting it. That way you avoid having to duplicate the common functionality.