Author image

Base Friend Design Pattern


Difficulty:
1/5

Just a software design pattern I have come up with, as a means to effectively and efficiently share code between different components/classes without breaking (too much) the rule of encapsulation. For these reasons I will classify it as a behavioral design pattern.

Design

We have a certain ResourceClass, that we wish to use its internals in various other UserClasses. How do we achieve interaction using the base friend pattern?

We can leverage the C++ friendship rules. We're aware that C++ friends break encapsulation, "friends invade our private life". We don't like that, we hate it. However.. remember that friendship is not inherited nor bidirectional. Given this we could create a base class for all our UserClasses and that class alone can be made a friend of the ResourceClass. Hence, that base class alone, call it BaseFriend, will have access to the ResourceClass. Now we can create some protected static functions in that BaseFriend class that will return the data we're interested in, located in ResourceClass. Now simply call those static functions from the derived UserClasses to get that data.

Github

A complete example will hopefully demonstrate the usefulness of this pattern.

Github repository link.


0 likes