0

Need of Bridge Pattern

Hi Refer code below I wrote to demo bridge pattern. Is this correct one or any suggestion on same? https://www.sololearn.com/en/compiler-playground/c9BiY9f22kb8 I have a doubt on the use case of this pattern. How it is useful? Color is simple class and it varies in real life depending on whether to color circle or rectangle. If it varies, how it is useful in bridge? If we call same method from circle and rectangle , how to differentiate the shape inside color class? https://sololearn.com/compiler-playground/c9BiY9f22kb8/?ref=app

15th May 2025, 5:09 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 1
Yes maybe that example is not the best. Since you wouldn't create a seperate class for each color in real life. But, the example is probably meant to be read like so: The shape knows how to color itself, and the color just holds color information, like what type of paint to use. A bucket of paint has no opinion on what you'll use it for. Perhaps a slighly better example: You have shapes (Circle, Square), and Renderers (PngRenderer, JpegRenderer) The PngRenderer can make .png files, using any shape. Perhaps the Shape class exports a list of points and the PngRenderer can use it to draw the image.
18th May 2025, 7:57 PM
Florian Schindler
Florian Schindler - avatar
+ 1
Say you write an app that has to support iOS, Android, Windows. To check if bluetooth is turned on you will need three bits of platform specific code. Then you also have react components that show whether bluetooth is turned on, or off, or is in pairing mode, with some fancy graphics. You could: a) Write 3*3 components, iOSBluetoothOff, AndroidBluetoothOff, etc b) Write 3 components BluetoothOff, BluetoothOn, BluetoothPairing, and handle the platform specific code in another class hierarchy The second choice is the obvious choice and also the better choice because you don't duplicate a bunch of code. It is also the bridge pattern. Your example could be solved by writing RedRectangle, BlueRectangle, RedCircle, BlueCircle classes but you can easily see the more colors and shapes there are the more code duplication there would be. I think this is one of those patterns that you really don't need a name for. If you have 20 colors and 10 shapes, nobody in their right mind would write 200 classes.
17th May 2025, 10:45 AM
Florian Schindler
Florian Schindler - avatar
0
I am not saying that bridge is not useful. I am wondering how it is useful. In my example code, color is just a cout statement. It does not matter which shape we are coloring just due to cout statement. In reality, don't we need to know what shape we are coloring ? If this is the case, we need to know each shape type inside color class making it difficult to manage
18th May 2025, 11:52 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Sounds good. Thanks for making me understand 🙂
18th May 2025, 8:24 PM
Ketan Lalcheta
Ketan Lalcheta - avatar