“This is the 30th day of my participation in the August Text Challenge.
preface
At the advanced end of the interview, there are often some questions about design patterns, and the answers are not good. Coincides with the activities of more challenges in August, I plan to spend a month to clarify the knowledge points about design patterns, to increase the confidence of my interview.
define
Separate the extraction part from its implementation part so that they can vary independently.
understand
The abstraction is separated from its implementation. This does not mean that the abstraction class is separated from its derived classes. Such a separation makes no sense. Implementation refers to the object that the abstraction class and its derived classes use to implement themselves.
The key to learning the bridge pattern is to understand the separation between the abstract and the implementation.
To illustrate, draw a red circle and a yellow triangle. There are two ways to do it,
-
First draw the circle, mix the red paint directly color, then continue to draw the triangle, mix the yellow paint directly color.
-
First mix the red paint and yellow paint, and then draw the circle and triangle, color separately.
So which way is good, it must be the second way, if you use the first way, the red paint is coupled to the circular shape.
Describe it in code:
Class colorShape {redCircle() {console.log('red circle')} yellowTriangle() {console.log('yellow triangle')// triangle}} let cs = new colorshape(); cs.redCircle() cs.yellowTriangle()Copy the code
We use colors as abstraction classes and shapes as concrete classes derived from color abstraction classes, of which circles and triangles are implemented by concrete classes.
class Color { constructor(name) { this.name = name } } class Shape { constructor(name, color) { this.name = name this.color = color } draw() { console.log(`${this.color.name} ${this.name}`) } } let red = new Color('red') let yellow = new Color('yello') let circle = new Shape('circle', red) circle.draw() let triangle = new Shape('triangle', yellow) triangle.draw()Copy the code
application
1. Expand methods for objects
Smoke like layer
Object.prototype.addMethod = function (name, fn) {
this[name] = fn;
}
Copy the code
Implementation layer
function Coordinate(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
var box = new Coordinate(20, 10, 10);
Copy the code
Extend methods for objects (bridge methods)
AddMethod ("init", function () {console.log(" init", function () {console.log(" init", function () {console.log(" init", function () {console.log(" init", function () {console.log(" init", function ()) {console.log(" init", function () {console.log(" init", function ()) {console.log(" init", function (); }); box.addMethod("getWidth", function () { console.log(this.y); });Copy the code