Strategy Pattern and Delegation

Learn how delegation helps avoid strong coupling.

We'll cover the following

Before moving on to discuss delegation, let’s understand the motivation behind it. Generally, after learning about inheritance, programmers make the mistake of using it very frequently.

Although inheritance is a very powerful concept, it increases the coupling between the base class and the derived class. For example, let’s say we have a base class named Sphere and a derived class named Football. Every time we make changes in the Sphere class, it will directly affect the derived class Football due to tight coupling. In some cases, it’s more desirable to avoid tight coupling. That is where delegation comes to the rescue.

In linguistics, delegation means “to transfer the authority of doing something from one person to another.” In computer science, delegation is an object-oriented principle in software engineering where one object delegates its operation to another object. So, instead of inheritance in delegation, one class will delegate its operation to another class.

To understand this better, let’s look at an example.

Example

Let’s take two classes named Sphere and Football. Instead of inheriting the Sphere class, the Football class will delegate its operation (in this case, calculating volume) to the Sphere class. The Football class will have an instance s of the Sphere class, and through that object, it will call the getVolume() method. The Football class must now explicitly forward requests to its sphere instance s, whereas previously, it would have inherited them.
In the diagram below, the Football class delegated its volume action to a sphere instance s.

Get hands-on with 1200+ tech skills courses.