Introduction to bridge pattern of Java design pattern

Bridge definition: it separates abstraction and behavior, which are independent but can be combined dynamically.

Why use bridge mode

Generally, when an abstract class or interface has multiple concrete subclasses, the relationships between these concretes may be as follows:

1. These concrete implementations are juxtaposed. For example, for pile driving, there are two concrete classes: square pile and circular pile; The piles in these two shapes are juxtaposed, and there is no conceptual repetition, so we just need to use inheritance. 2. In practical application, it is often possible to have conceptual overlap between these multiple concrete classes. Then we need to separate the common part of abstraction and the common part of behavior. Originally, we were prepared to put them in one interface. Now we need to design two interfaces to place abstraction and behavior respectively.

For example, a cup of coffee can be divided into medium cup and large cup, as well as milk or no milk. If you use simple inheritance, there is conceptual overlap between the four specific implementations (medium cup and large cup with milk without milk), because there are medium cup with milk and medium cup without milk. If you implement two inheritance on the medium cup layer, it is obviously chaotic and has poor scalability. Then we use the bridge pattern to implement it.

How to implement bridge mode

Take the coffee mentioned above as an example. We originally intended to design only one interface (abstract class). After using bridge mode, we need to separate abstraction from behavior. Adding milk and not adding milk belong to behavior, and we abstract them into a special behavior interface.

First look at the interface code of the abstract part:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>