Structural Patterns — overview
These articles are a part of the design pattern series I’m writing to teach developers how to write clean and readable code that scale.
The main overview page can be found here.
Structural Patterns describe the design method, identifying a simple way to implement class relationships. They help to combine objects for larger structure.
There are few types:
- Adapter/Wrapper
- Bridge
- Facade
- Proxy
Adapter/Wrapper
If you have two or more incompatible objects, you can use ‘Wrapper’ (I prefer this description rather than an adapter) to let them interact with each other.
In the diagram above you can see two interfaces: ‘ICar’ and ‘IElectricCar’ and two objects ‘Car’ and ‘ElectricCar’. ‘Car’ has a ‘Refuel()’ method which is responsible for filling the tank with fuel. A manufacturer wants to manufacture a new type of car, which needs new functionalities. It doesn’t use gasoline, instead, it uses electricity. The manufacturer also wants to use this new method with the existing line of cars. The only thing which needs to be done for this to happen is to expand the ‘Refuel()’ method in the Car class to understand the new type and invoke the ‘Charge()’ method from the ‘IElectricCar’ interface.”
Sample code:
Another way to implement:
This example solve our problem, but it is not an example of the adapter pattern. I only want to show to you that for all problems are possible different solutions.
Bridge
This pattern separates abstraction from its implementation. So you can modify them independently. It is like a bridge between an implemented class and an abstract class. I usually use it in places where I need to make changes in the implementation but it does not affect the clients.
In the following schema, you can see two classes with the same functionality implemented in different way.
The code below present all functionality about Bridge Design Pattern:
Here is a sample of the client:
Here we see another interface implementation, but this time describing the Bridge Pattern.
Facade
Facade Design Pattern is especially used when the system is very complex because the system has a large number of interdependent classes. A single class that represents an entire complex system.
Sample code below:
Proxy
Proxy Design Pattern that aims to create an object that replaces another object. It is usually used to control the creation of costly objects on demand and control access to them.
The ‘MSSQLProvider’ object should be created only when necessary. It is managed by a separate ‘DataBaseProxy’ class.
The simple example of the client:
Summary
Structural Patterns relate to the composition of objects, classes and interfaces.
I invite you to read the other articles in this series:
You can follow/contact me through this link: Daniel Jankowski.
This article is the property of Netcompany.
References: