Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use C++ bridging mode

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report