可读性:★★★✰✰ 理解难度:★★★✰✰
概述
拓展类 vs 拓展函数。
有时,我们希望能够灵活地添加新的数据类型,这时可以使用对象。
有时,我们希望能够灵活地添加新行为,这时可以使用数据类型和过程。
优秀的开发者不带成见地依据手边的工作选择其中一种适合的手段。
一、拓展类
多态式封装
// 正方形类
class Square extends Shape {
constructor(position, side) {
this.position = position;
this.side = side;
}
getArea() {
return this.side * this.side;
}
}
// 长方形类
class Rectangle extends Shape {
constructor(position, height, width) {
this.position = position;
this.height = height;
this.width = width;
}
getArea() {
return this.height * this.width;
}
}
// 圆形类
class Rectangle extends Shape {
constructor(position, radius) {
this.position = position;
this.radius = radius;
this.PI = 3.1415926
}
getArea() {
return this.PI * this.radius * this.radius;
}
}
通过封装不同的形状类来适配不同的业务场景。
二、拓展方法
过程式代码
// 正方形类
class Square extends Shape {
constructor(position, side) {
this.position = position;
this.side = side;
}
}
// 长方形类
class Rectangle extends Shape {
constructor(position, height, width) {
this.position = position;
this.height = height;
this.width = width;
}
}
// 圆形类
class Rectangle extends Shape {
constructor(position, radius) {
this.position = position;
this.radius = radius;
}
}
class Geometry {
constructor() {
this.PI = 3.1415926;
}
area(shape) {
if (shape instanceof Square) {
return shape.side * shape.side;
} else if (shape instanceof Rectangle) {
return shape.height * shape.width;
} else if (shape instanceof Circle) {
return this.PI * shape.radius * shape.radius;
}
}
}
通过修改area方法来实现不同场景的调用。
三、结论
面向对象代码便于在不改动既有函数的前提下添加新类;
过程式代码(使用数据结构的代码)便于在不改动既有数据结构的前提下添加新函数。
这两种方式,可以是二元对立的,也可以是相互融合的,就看开发者如何去选择与结合。
本文参考《代码整洁之道》(Robert C. Martin著,韩磊译)。
浙江大华技术股份有限公司-软研-智慧城市产品研发部招聘高级前端,欢迎来撩,有意向可发送简历到chen_zhen@dahuatech.com,长期有效
上一篇:五、格式
下一篇:七、对象和数据结构