The bridging design pattern is the basis of many other design patterns, such as the decoration pattern and the proxy pattern, which can be seen more or less in its shadow. One of the most important features in object-oriented design is inheritance. However, as the function of extending classes There are two ways - inheritance and bridging. In my simple understanding, bridging is to give up the use of inheritance to extend the class, but to extend the class by including another object with certain functions. Let's look at the two structures.
First we assume that there is a requirement, a graphics interface, and then there are graphics classes such as rectangle, square, circle, etc. We need graphics of various colors. Let’s use inheritance and bridging to realize this requirement. .
let Shape = function(color) { this.color = color; }; Shape.prototype.setColor = function(color) { this.color = color; }; Shape.prototype.draw = function() { new Error(); }
let Rectangle = function (color) { Shape.call(this, color); }; extend(Rectangle, Shape); Rectangle.prototype.draw = function () { color.bepaint("长方形"); }; let Square = function (color) { Shape.call(this, color); }; extend(Square, Shape); Square.prototype.draw = function () { color.bepaint("正方形"); } let Circle = function (color) { Shape.call(this, color); }; extend(Circle, Shape); Circle.prototype.draw = function () { color.bepaint("圆型"); };
let Color = function() { }; Shape.prototype.bepaint = function() { new Error(); };
let Red = function () { Color.call(this); }; extend(Red, Color); Red.prototype.bepaint = function(shape) { console.log("白色的" + shape); }; let Green = function () { Color.call(this); }; extend(Green, Color); Green.prototype.bepaint = function(shape) { console.log("绿色的" + shape); }; let Blue = function () { Color.call(this); }; extend(Blue, Color); Blue.prototype.bepaint = function(shape) { console.log("蓝色的" + shape); };
let red = new Red(); //正方形 let square = new Square(); //红色的正方形 square.setColor(red); square.draw(); //长方形 let rectange = new Rectangle(); //红色长方形 rectange.setColor(red); rectange.draw();
The bridge mode achieves the decoupling of abstraction and implementation. The two of them are independent of each other and will not affect each other. For two independently changing dimensions, the bridge mode is perfect.Related recommendations:
A brief introduction to the structural flyweight pattern of js design pattern
Example of service locator pattern of php design pattern Detailed explanation
Detailed explanation of the delegation pattern of PHP design pattern
The above is the detailed content of Detailed explanation of js bridge design pattern. For more information, please follow other related articles on the PHP Chinese website!