Searching for specific element in Composite pattern

Suppose I have a simple composite pattern structure:

  • abstract class User

  • leaf class PersonalUser

  • composite class GroupUser with a std::vector<User*> users container as its member variable

and a method bool GroupUser::findUser(User* u) which returns true if the user u is found in the users container (which naturally consists of other PersonalUser or GroupUser objects)

Now, I'd like to define that function recursively of course, so I need to go through each User in users vector, and compare with u, but I won't know if the User is a PersonalUser or GroupUser, so my question is:

Do I have to define a virtual function char User::returnType() which will tell me which type of User it is, or is there a better/smarter way to go down the tree and look for the User?

p.s. there is of course a method like bool areEqual(User*, User*) by which we can compare users :)

Answers


You can add the FindUser member function as a virtual to the abstract class User, and make it return true if the user being searched for is the current user (Personal or Group).

In GroupUser you can override FindUser and delegate any call to all the contained Users if the User being searched for isn't the current GroupUser.


Need Your Help

HTML table: columns with minimum width and break-word

html css

I want to display the following table: