Here is an example of Photoshop, which we use most frequently.
In Photoshop, there are many graphical tools, such as stars, such as squares, and circles.
In Photoshop, there are many colors for us to choose.
The red stars and the green stars are generated. Red Square, green square, and so on.
Look at the generated tree:
Now there are three types of images and three colors, so we can declare a total of nine classes. Of course, we are not the secondary parent class in the intermediate process.
If we have 18 images and 12 colors, we need to write 18*12 classes, and then add 12 color classes and a total parent class, in total, we need 12*18 + 12 + 1 = 229 classes.
Multi-Inheritance
It is no longer appropriate to describe this model with multiple inheritance. Declare 18 graphics classes, then declare 12 color classes, and then use the specific graphics class to inherit from multiple classes.
Let's take a look at this illustration:
The intricate lines may seem messy, but I think everyone should understand this.
It is easy to understand, but at this time we will look at the number of this class:
Color 12 + color parent class 1 + graphics 18 + graphics parent class 1 + 12*18, this number seems bigger than the number we used before.
Maybe I will argue for him that he sacrificed space in exchange for readability,
Bridging Mode
In this case, let's calculate the total number of classes:
12 color classes + 18 graphics classes + 1 our graphics = 31 classes
Class icolor {}
Class redcolor: icolor {}
Class bluecolor: icolor {}
Class yellowcolor: icolor {}
Class igraphics {}
Class rectangle: igraphics {}
Class star: igraphics {}
Class round: igraphics {}
Class Photoshop
{
Icolor color;
Igraphics graphics;
Public Photoshop (icolor C, igraphics g)
{
This. Color = C;
This. Graphics = g;
}
Public void draw ()
{
Cout <color. GetType () <Endl;
Cout <graphics. GetType () <Endl;
}
}
Bridge pattrern: separates abstract parts from implementation parts so that they can all change independently.
Deep Dive:
1. interfaces are behavior contracts, while abstract classes are feature abstractions. One is can do and the other is.
2. object-oriented design principle: combination is better than inheritance.
The above Code requires more than color and shape, so I have to write a lot of attributes, which is troublesome.
And more importantly, if I have such a requirement, I now have 12 colors and 3 shapes, which are square, round, and star. There are two pen types, pencil and crayons. However, my pencil now only corresponds to square and stars, and the crayons only correspond to circles and stars. That is to say there is no circular pencil or square crayon. In this case, isn't my combination a waste? And the customer may be wrong in combination?
Yes. Do not consider combinations. Repeat what I love to say: the mode is for change, not for mode. We just need to pull out the change point!
In this case, we should write a stable department.