三种编码方式
一个开灯设置颜色的示例,使用三种编码方式来实现。分别是:脚本化编程、具有函数思维的过程化编程以及面向对象编程。
脚本化编程:
class Light {
status: string
color: string
}
function main() {
const light = new Light()
if (light.status === "on") {
throw new Error("The light is on")
}
light.status = "on"
light.color = "red"
}
具有函数思维的过程化编程:
class Light {
status: string
color: string
}
function open(light: Light) {
if (light.status === "on") {
throw new Error("The light is on")
}
light.status = "on"
}
function setColor(light: Light, color: string) {
if (light.status !== "on") {
throw new Error("The light is not on")
}
light.color = color
}
function main() {
const light = new Light()
open(light)
setColor(light, "red")
}
面向对象编程:
class Light {
#status: string
#color: string
public on() {
if (this.#status === "on") {
throw new Error("The light is on")
}
this.#status = "on"
}
public set color(color: string) {
if (this.#status !== "on") {
throw new Error("The light is not on")
}
this.#color = color
}
}
function main() {
const light = new Light()
light.on()
light.color = "red"
}
都是 Light
咋有那么多实现,你慢慢品...,你平常用那一种方式呢?