How to use C++ bridging mode
This article introduces the knowledge of "how to use C++ bridging mode". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
C++ involves mode bridging mode (bridge Pattern)
Consider this question:
You need to get a figure, which can be a circle or a square, so that the color of a rectangle can be blue, red or green, if the design is written to death in this case.
See that there are 3 "3" 9 classes, but more graphics and colors? So if it becomes a basically impossible task, then in this case we need a design pattern called bridging, which also works on the same principle.
Through the decoupling of virtual functions, the graphic abstract class represents the color through a pointer (dependency) of the input color abstract class, and then by saving it in an aggregate color abstract class pointer member, here
Through the decoupling of these two graphics abstract classes and color abstract classes, at the same time, the combination of any color and any graphics can be realized, which is also a very magical design pattern.
The following is the pattern diagram:
The following is the code implementation of the above question:
The output is:
I'm bule rectangle
I'm red rectangle
I'm green square
I'm bule square
Code:
# include
Using namespace std
/ / Color virtual interface
Class colour
{
Public:
Virtual void getcol () = 0
Virtual ~ colour () {}
}
/ / shape virtual interface
Class graph
{
Public:
Virtual void setcol (colour* col) = 0; / / dependent bridging
Virtual ~ graph () {}
Protected:
Colour* col; / / aggregation bridging
}
/ / specific implementation of color
Class red:public colour
{
Public:
Virtual void getcol ()
{
Coutgetcol ()
Coutcol = col
}
Void print ()
{
This- > col- > getcol ()
Cout