Notes on the problem each pattern solves, its implementation, and its limits, following the original chapter and example order.
Running the examples:Run JavaScript blocks separately to avoid redeclaring classes. Supplemental calls within a section follow their corresponding definitions. Open HTML examples in a browser and split the module example into the two files described. Original Chinese code comments and demo labels are retained; headings and explanatory prose are translated.
01 Constructor pattern
A constructor initializes each instance. Defining a method inside it creates a separate function per instance; the next example moves shared behavior onto the prototype.
// let employee1 = {
// name: "kerwin",
// age: 100,
// };
// let employee2 = {
// name: "jack",
// age: 18
// }
// 用构造函数
// 构造函数内定义的方法会为每个实例创建一个函数,可移到原型共享。
function Employee(name, age) {
this.name = name
this.age = age
this.say = function () {
console.log(`${this.name} + ${this.age}`)
}
}
let employee1 = new Employee("kerwin", 100)
let employee2 = new Employee("jack", 18)
employee1.say()
employee2.say()
02 Prototype pattern
This example demonstrates JavaScript prototype sharing: Employee instances reuse prototype.say. It is not a full example of the GoF Prototype pattern, which creates objects by copying existing ones.
function Employee(name, age) {
this.name = name
this.age = age
}
// 挂在原型链上
Employee.prototype.say = function () {
console.log(`${this.name} + ${this.age}`)
}
let employee1 = new Employee("kerwin", 100)
let employee2 = new Employee("jack", 18)
employee1.say()
employee2.say()
03 Classes: constructors and prototypes
Class syntax groups construction and shared behavior. Ordinary instance methods live on the prototype rather than being recreated by a function assignment for every instance.
class Employee {
constructor(name, age) {
this.name = name
this.age = age
}
say() {
console.log(`${this.name} + ${this.age}`)
}
}
let employee1 = new Employee("kerwin", 100)
let employee2 = new Employee("jack", 18)
employee1.say()
employee2.say()
04 Factory pattern
Centralize user creation by role. The second example now accepts the missing role parameter. Static methods belong to the class and can be inherited; they are not called directly on instances. The pages list describes frontend navigation; authorization still belongs on the server.
// ES5
// 由一种工厂对象决定创建某一种产品对象的实例
// 主要用来创建同一类对象
function UserFactory(role) {
function User(role, pages) {
this.role = role
this.pages = pages
}
switch (role) {
case "superadmin":
return new User("superadmin", [
"home",
"user-manage",
"right-manage",
"news-manage",
])
case "admin":
return new User("admin", ["home", "user-manage", "news-manage"])
case "editor":
return new User("editor", ["home", "news-manage"])
default:
throw new Error("parameter error!")
}
}
let u1 = UserFactory("admin")
console.log(u1)
// ES6
/*
简单工厂的优点在于,你只需要一个正确的参数,就可以获取到你所需要的对象,而不需要知道其创建的具体细节。但是函数内包含了所有对象逻辑和判断逻辑的代码,每增加新的构造函数还需要修改判断代码逻辑代码。
简单工厂只能作用于创建的对象数量较少,对象逻辑不复杂时使用。
*/
class User {
constructor(role, pages) {
this.role = role
this.pages = pages
}
// 静态方法通过类访问,子类可继承。
static UserFactory(role) {
switch (role) {
case "superadmin":
return new User("superadmin", [
"home",
"user-manage",
"right-manage",
"news-manage",
])
case "admin":
return new User("admin", ["home", "user-manage", "news-manage"])
case "editor":
return new User("editor", ["home", "news-manage"])
default:
throw new Error("parameter error!")
}
}
}
const admin = User.UserFactory("admin")
console.log(admin.pages)
05 Abstract factory pattern
The original heading and example are retained. The code demonstrates a base class, specialized subclasses, and a factory selecting a constructor. A full Abstract Factory exposes creation interfaces for several related products in a family. Here, throwing from dataShow enforces the subclass implementation at runtime.
// 抽象工厂模式并不直接生成实例,而是用于对产品类簇的创建
class User {
constructor(name, role, pages) {
this.name = name
this.role = role
this.pages = pages
}
welcome() {
console.log("欢迎回来", this.name)
}
dataShow() {
throw new Error("抽象方法需要被实现")
}
}
class SuperAdmin extends User {
constructor(name) {
super(name, "superadmin", ["home", "user-manage", "news-manage"])
}
dataShow() {
console.log("superadmin-datashow")
}
}
class Admin extends User {
constructor(name) {
super(name, "admin", ["home", "news-manage"])
}
dataShow() {
console.log("admin-datashow")
}
}
class Editor extends User {
constructor(name) {
super(name, "editor", ["home", "news-manage"])
}
dataShow() {
console.log("editor-datashow")
}
}
function getAbstractUserFactory(role) {
switch (role) {
case "superadmin":
return SuperAdmin
case "admin":
return Admin
case "editor":
return Editor
default:
throw new Error("parameter error!")
}
}
let userClass = getAbstractUserFactory("editor")
let user = new userClass("kerwin")
user.dataShow()
06 Builder pattern
Delegate construction steps to a builder while Creator controls init → getData → render. This is a simplified workflow; a complete product builder also defines how the product is assembled and returned.
/*
建造者模式(builder pattern) 属于创建者模式的一种,提供一种创建复杂对象的方式。它将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
建造者模式是一步一步的创建一个复杂的对象,它允许用户只通过指定复杂的对象的类型和内容就可以搭建他们,用户不需要指定内部的具体的构造内容细节。
建造者模式是将一个复杂对象的 构建层 与其 表示层 相互分离,同样的构建过程可采用不同的表示。工厂模式主要是为了创建对象实例或者类簇(抽象工厂),关心的是最终产出(创建的是什么),而不关系过程。
而建造者模式关心的是创建的过程
*/
class Navbar {
init() {
console.log("navbar-init")
}
getData() {
console.log("navbar-getData")
}
render() {
console.log("navbar-render")
}
}
class List {
init() {
console.log("List-init")
}
getData() {
console.log("List-getData")
}
render() {
console.log("List-render")
}
}
class Creator {
startBuild(builder) {
builder.init()
builder.getData()
builder.render()
}
}
const op = new Creator()
op.startBuild(new Navbar())
op.startBuild(new List())
07 Singleton pattern
Cache one instance in the example's scope. The ES5 version now returns instance on every call, including the first. Later arguments do not reinitialize it. The third block is browser HTML that reuses one modal element.
// ES5
/*
1.保证一个类仅仅只有一个实例,并提供一个访问它的全局访问点
2.主要解决一个全局使用的类频繁地创建和销毁,占用内存
*/
let Singleton = (function () {
function User(name, age) {
this.name = name
this.age = age
}
let instance
return function (name, age) {
if (!instance) {
instance = new User(name, age)
}
return instance
}
})()
let a = Singleton("kerwin", 18)
console.log(a)
a = Singleton("jack", 28)
console.log(a)
// ES6
class Singleton {
constructor(name, age) {
if (!Singleton.instance) {
this.name = name
this.age = age
Singleton.instance = this
}
return Singleton.instance
}
}
let user = new Singleton("kerwin", 18)
console.log(user)
user = new Singleton("jack", 18)
console.log(user)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.kerwin-model {
position: fixed;
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: yellow;
display: none;
}
</style>
</head>
<body>
<!-- <div class="kerwin-model">
login in!
</div> -->
<button id="open">open</button>
<button id="close">close</button>
<script>
class Model {
constructor() {
if (!Model.instance) {
this.element = document.createElement("div")
this.element.innerHTML = "login in!"
this.element.className = "kerwin-model"
this.element.style.display = "none"
document.body.appendChild(this.element)
Model.instance = this
}
return Model.instance
}
}
// 创建model
const model = new Model()
document.querySelector("#open").onclick = function () {
model.element.style.display = "block"
}
document.querySelector("#close").onclick = function () {
model.element.style.display = "none"
}
</script>
</body>
</html>
08 Decorator pattern
Wrap a function with before and after behavior while preserving this, arguments, and the original return value. These prototype extensions are teaching examples, not @decorator syntax; ordinary higher-order functions avoid modifying built-in prototypes. The after callback runs only after a normal return.
/*
装饰器模式可以很好的对已有的功能进行拓展,这样不会更改原有的代码,对其他的业务产生影响,这样方便我们在较少的改动下对软件进行拓展
*/
Function.prototype.before = function (beforeFn) {
let _this = this
return function () {
// 先进行前置函数调用
beforeFn.apply(this, arguments)
// 执行原来的函数
return _this.apply(this, arguments)
}
}
Function.prototype.after = function (afterFn) {
let _this = this
return function () {
let res = _this.apply(this, arguments)
afterFn.apply(this, arguments)
return res
}
}
function test() {
console.log("111111")
}
// test = new Function()
let test1 = test
.before(function () {
console.log("000000")
})
.after(function () {
console.log("222222")
})
test1()
09 Adapter pattern
Adapt TencentMap.show to the display interface expected by the caller. renderMap does not need to know each provider's original method name.
// 将一个类的接口转化成客户希望的另一个接口
// 适配器模式让那些接口不兼容的类可以一起工作
class TencentMap {
show() {
console.log("开始渲染腾讯地图")
}
}
class BaiduMap {
display() {
console.log("开始渲染百度地图")
}
}
class TencentAdapater extends TencentMap {
constructor() {
super()
}
display() {
this.show()
}
}
function renderMap(map) {
map.display()
}
renderMap(new TencentAdapater())
renderMap(new BaiduMap())
10 Strategy pattern
Store bonus algorithms in a strategy table keyed by level and expose a consistent entry point. Unknown levels now produce an explicit error instead of calling undefined.
/*
策略模式定义了一系列的算法,并将每一个算法封装起来,使得他们可以相互替换,且算法的变化不影响使用算法的客户。
策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分开,委派给不同的对象进行管理。
主要用于类似if...else...场景,具有良好的拓展性
*/
// function calBonus(level, salary) {
// if (level === "a") {
// return salary * 4;
// } else if (level === "b") {
// return salary * 3;
// } else {
// return salary * 2;
// }
// }
let strategry = {
a: (salary) => {
return salary * 4
},
b: (salary) => {
return salary * 3
},
c: (salary) => {
return salary * 2
},
}
function calBonus(level, salary) {
const strategy = Object.hasOwn(strategry, level)
? strategry[level]
: undefined
if (!strategy) throw new Error("Unknown bonus level")
return strategy(salary)
}
console.log(calBonus("a", 10000))
console.log(calBonus("b", 2000))
console.log(calBonus("c", 5000))
11 Proxy pattern
A proxy controls access to a real object. The first example checks a fee through an agent object; the second intercepts properties with Proxy. Its set trap now delegates valid writes to Reflect.set and returns a success boolean.
/*
代理模式(proxy),为其他对象提供一种代理以控制对这个对象的访问
代理模式使得代理对象控制具体对象的引用。代理几乎可以是任何对象:文件,资源,内存中的对象,或者一些难以复制的东西
*/
class Star {
play() {
console.log("演戏")
}
}
class StarProxy {
constructor() {
this.superStar = new Star()
}
talk(price) {
if (price >= 100000) {
this.superStar.play()
} else {
throw new Error("价钱不合适")
}
}
}
let jr = new StarProxy()
jr.talk(200000)
let star = {
name: "tiechui",
workprice: 10000,
}
let proxy = new Proxy(star, {
get(target, key, receiver) {
if (key === "workprice") {
console.log("访问了")
}
return Reflect.get(target, key, receiver)
},
set(target, key, value, receiver) {
if (key === "workprice") {
console.log("设置了")
if (value > 10000) {
console.log("可以合作")
} else {
throw Error("价格不合适")
}
}
return Reflect.set(target, key, value, receiver)
},
})
console.log(proxy.workprice)
proxy.workprice = 20000
console.log(star.workprice)
12 Observer pattern
Subject keeps observer references and calls update during notify. The subject triggers notifications. This example removes the first observer after one second and notifies the remaining observer after two seconds. Its notification interface does not classify events by name.
/*
观察者模式分为 观察目标 和 观察者 两类对象
一个目标可以有任意数目的与之相依赖的观察者
观察目标通过 notify 通知已注册的观察者
当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新,解决了主体对象与观察者之间功能的耦合,即一个对象状态改变给其他对象通知的解决
优势:目标者与观察者,功能耦合度降低,专注自身的功能逻辑;观察者通过 update 接收通知;当前实现仍是同步调用。
边界:本例只有统一的 notify,没有按事件名称细分通知
*/
class Subject {
constructor() {
this.obeservers = []
}
add(obeserver) {
this.obeservers.push(obeserver)
}
remove(obeserver) {
// slice
// filter
this.obeservers = this.obeservers.filter((item) => item !== obeserver)
}
notify() {
this.obeservers.forEach((item) => {
console.log(item)
item.update()
})
}
}
class Obeserver {
constructor(name) {
this.name = name
}
update() {
console.log("update!!!", this.name)
}
}
const subject = new Subject()
const obeserver1 = new Obeserver("kerwin")
const obeserver2 = new Obeserver("jack")
subject.add(obeserver1)
subject.add(obeserver2)
setTimeout(() => {
subject.remove(obeserver1)
}, 1000)
setTimeout(() => {
subject.notify()
}, 2000)
13 Publish–subscribe pattern
Publishers and subscribers communicate through an event hub. The first block intentionally remains incomplete: it ignores type, so publishing AAA also runs testB. The second dispatches by event name and supports unsubscribe; its event table has no prototype to avoid inherited-key collisions.
/*
1.此处的观察者示例由目标保存观察者引用
2.发布订阅通过事件中心调度,发布者与订阅者不必直接引用对方
*/
// publish 发布
// subscribe 订阅
// 残缺版 依旧没能实现调度
const PubSub = {
list: [],
publish(type) {
this.list.forEach((item) => item())
},
subscribe(type, cb) {
this.list.push(cb)
},
}
function testA() {
console.log("testA")
}
function testB() {
console.log("testB")
}
PubSub.subscribe("AAA", testA)
PubSub.subscribe("BBB", testB)
PubSub.publish("AAA")
const PubSub = {
massage: Object.create(null),
publish(type, data) {
if (!this.massage[type] || this.massage[type].length === 0) return
this.massage[type].forEach((item) => item(data))
},
subscribe(type, cb) {
if (!this.massage[type]) {
this.massage[type] = [cb]
} else {
this.massage[type].push(cb)
}
},
unsubscribe(type, cb) {
if (!this.massage[type] || this.massage[type].length === 0) return
if (!cb) {
// 没有指定的cb 取消当前type所有的cb
this.massage[type] = []
} else {
// 取消指定的哪一个
this.massage[type] = this.massage[type].filter((item) => item !== cb)
}
},
}
function testA(data) {
console.log("testA", data)
}
function testB(data) {
console.log("testB", data)
}
function testC(data) {
console.log("testC", data)
}
PubSub.subscribe("AAA", testA)
PubSub.subscribe("BBB", testB)
PubSub.subscribe("CCC", testC)
PubSub.unsubscribe("CCC")
PubSub.publish("CCC", 2333)
PubSub.publish("BBB", 7788)
14 Module pattern
A closure hides local state behind a public interface. The ESM example spans two files: put the first block's import in an entry module and save the second block as 14.ESM.js beside it. Browser entry scripts need type="module". Default import names are freely chosen and need not match the filename. Class private fields use #; the original ES2020 attribution was removed.
/*
模块化模式最初被定义为在传统软件工程中为类提供私有的公共封装的一种方法
能够使一个单独的对象拥有 公共/私有 的方法和变量,从而屏蔽来自全局作用域的特殊部分。
这可以减少我们的函数名与页面中其他脚本区域内定义的函数名冲突的可能性。
类私有字段使用 # 前缀,只能在声明它的类内部访问。
*/
// 1.闭包
const obj = (function () {
let count = 0
return {
increase() {
return count++
},
decrease() {
return count--
},
}
})()
console.log(obj)
// 2.ESM
// 默认导入名可自定义,路径必须正确指向导出模块。
import ESM from "./14.ESM.js"
let arr = [23, 13, 23, 3213]
console.log(ESM.mySum(arr))
function mySum(arr) {
let count = 0
arr.forEach((element) => (count += element))
return count
}
export default {
mySum,
}
15 Bridge pattern
Connect independently varying dimensions through composition: car models and engines, or UI components and animations. The second example now passes this.ele to animation methods so one animation implementation can serve different components.
/*
桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立的变化
使用场景:一个类存在两个或者多个独立变化的维度,且这两个维度都需要进行拓展
优点:
把抽象与现实隔离开,使得他们都可以独立的变化
缺点:
引入额外的对象和接口,需要权衡结构复杂度;性能影响应结合实际测量
*/
function Audi1(engine) {
this.engine = engine
}
Audi1.prototype.platform = function () {
console.log("audi1 platform")
}
Audi1.prototype.loadEngine = function () {
this.engine.run()
}
function Audi2(engine) {
this.engine = engine
}
Audi2.prototype.platform = function () {
console.log("audi2 platform")
}
Audi2.prototype.loadEngine = function () {
this.engine.run()
}
function V6() {
this.run = function () {
console.log("V6发动机")
}
}
function V8() {
this.run = function () {
console.log("V8发动机")
}
}
function V12() {
this.run = function () {
console.log("V12发动机")
}
}
let audi1 = new Audi1(new V6())
let audi2 = new Audi2(new V12())
audi1.loadEngine()
audi2.loadEngine()
const Animation = {
bounce: {
show(ele) {
console.log(ele, "弹跳显示")
},
hide(ele) {
console.log(ele, "弹跳隐藏")
},
},
slide: {
show(ele) {
console.log(ele, "滑动显示")
},
hide(ele) {
console.log(ele, "滑动隐藏")
},
},
rotate: {
show(ele) {
console.log(ele, "旋转显示")
},
hide(ele) {
console.log(ele, "旋转隐藏")
},
},
}
function Toast(ele, animation) {
this.ele = ele
this.animation = animation
}
Toast.prototype.show = function () {
this.animation.show(this.ele)
}
Toast.prototype.hide = function () {
this.animation.hide(this.ele)
}
let toast1 = new Toast("div1", Animation.bounce)
toast1.show()
setTimeout(() => {
toast1.hide()
}, 1000)
16 Composite pattern
Folders and files expose the same scan interface. A caller starts at the root without distinguishing leaves from containers. This example assumes a tree and does not detect cycles.
/*
组合模式在对象间形成 树形结构
组合模式中 叶子对象 和 组合对象通过统一接口处理
无需关心对象有多少层 调用时只需要在根部进行调用
它在我们树形结构的问题中,模糊了简单元素和复杂元素的概念,
客户程序可以向处理简单元素一样来处理复杂元素,
从而使得客户程序与复杂元素的内部结构解耦
递归
*/
// 写一个遍历文件夹
const Folder = function (folder) {
this.folder = folder
// 保存子文件夹 或者文件
this.list = []
}
Folder.prototype.add = function (res) {
this.list.push(res)
}
Folder.prototype.scan = function () {
console.log("扫描文件夹", this.folder)
for (let index = 0; index < this.list.length; index++) {
this.list[index].scan()
}
}
const File = function (file) {
this.file = file
}
File.prototype.scan = function () {
console.log("扫描文件", this.file)
}
// 根
let rootFolder = new Folder("root")
// 子文件夹
let htmlFolder = new Folder("html")
let jsFolder = new Folder("js")
let cssFolder = new Folder("css")
//文件
let html4 = new File("html4")
let html5 = new File("html5")
let css2 = new File("css2")
let css3 = new File("css3")
let es5 = new File("es5")
let es6 = new File("es6")
rootFolder.add(htmlFolder)
rootFolder.add(cssFolder)
rootFolder.add(jsFolder)
htmlFolder.add(html4)
htmlFolder.add(html5)
cssFolder.add(css2)
cssFolder.add(css3)
jsFolder.add(es5)
jsFolder.add(es6)
rootFolder.scan()
17 Command pattern
Invoker starts a request, Command encapsulates it, and Receiver performs the work. The caller depends on a command interface rather than on the receiver's implementation.
/*
有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么。需要一种松耦合的方式来设计程序,使得发送者和接收者都能够消除彼此之间的耦合关系。
命令模式由三种角色构成:
1.发布者invoker (发送命令,调用命令对象,不知道如何执行与谁执行)
2.接收者receiver (提供对应接口处理请求,不知道谁发起请求)
3.命令对象command (接受命令,调用接受者对应处理发布者的请求)
*/
class Receiver {
// 接受类
execute() {
console.log("接收者执行请求")
}
}
class Command {
// 命令类
constructor(receiver) {
this.receiver = receiver
}
execute() {
console.log("命令对象 => 接收者如何处理")
this.receiver.execute()
}
}
class Invoker {
// 发布类
constructor(command) {
this.command = command
}
order() {
console.log("发布请求")
this.command.execute()
}
}
const order = new Command(new Receiver())
const client = new Invoker(order)
client.order()
18 Macro command pattern
Group commands and execute them in insertion order. A macro also exposes execute, allowing nested composition. This example handles synchronous commands only.
/*
组合模式 + 命令模式
一组命令的集合
*/
class MacroCommand {
constructor() {
this.list = []
}
add(command) {
this.list.push(command)
}
execute() {
this.list.forEach((element) => element.execute())
}
}
const Tabs = {
execute() {
console.log("选项卡执行")
},
}
const Swipe = {
execute() {
console.log("轮播执行")
},
}
const macrocommand = new MacroCommand()
macrocommand.add(Tabs)
macrocommand.add(Swipe)
macrocommand.execute()
19 Template method pattern
Fix the getData → render sequence while accepting implementations for the varying steps. The original params argument now supplies those steps, and the invocation demonstrates customization while preserving the function-factory form.
/*
模板方法模式由两部分组成:
1.抽象父类
2.实现子类
通常在抽象方法中封装了子类算法框架,包括实现一些公共方法以及封装子类中所有方法的执行顺序。
子类通过继承这个抽象类,也继承整个算法结构,并且可以选择重写父类方法。
*/
let Container = function (params = {}) {
let F = function () {}
F.prototype.init = function () {
this.getData()
this.render()
}
F.prototype.getData =
params.getData ||
function () {
console.log("getData")
}
F.prototype.render =
params.render ||
function () {
console.log("render")
}
return F
}
let Myclass = Container({
getData() {
console.log("custom getData")
},
render() {
console.log("custom render")
},
})
new Myclass().init()
20 Iterator pattern
Separate traversal from the work performed on each item. myEach visits an array through a callback. The second example now includes for...of to demonstrate the iterable protocol; ordinary objects are not iterable by default.
/*
迭代器模式是指提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象内部表示。迭代器模式可以把迭代的过程从业务逻辑中分离出来,在使用迭代器模式之后,即使不关心对象的内部构造,也可以按顺序访问其中每个元素。
1.为遍历不同数据结构的"集合"提供统一的接口
2.能遍历访问"集合"数据中的项,不关心项的数据结构
*/
// 迭代方法 和 业务逻辑 分离
let myEach = function (arr, callback) {
for (let i = 0; i < arr.length; i++) {
callback(i, arr[i])
}
}
myEach([12, 32, 321, 213, 1, 23], function (key, value) {
console.log(key, value)
// let oli = document.createElement("li")
// oli.innerHTML = value
// list.appendChild(oli)
})
// es6 Iterator
// Array map set String arguments NodeList(节点对象)
// 可以使用 for (let i of arr)
let arr = ["kerwin", "jack", "jake"]
console.log(arr)
for (const name of arr) {
console.log(name)
}
21 Chain of Responsibility pattern
Link validation rules so each node stops or forwards a request. The browser example corrects Number, the length check, addRule chaining, and the button handler. It explicitly looks up DOM elements and stops safely at the end. Empty, nonnumeric, and short inputs stop at their corresponding rules; only valid inputs reach the final action.
/*
使多个对象都有机会处理请求,从而避免了请求的发送者与多个接收者直接的耦合关系
将这些接收者链接成一条链,顺着这条链传递该请求,直接找到能处理该请求的对象
就是链表的调用
*/
<body>
<input type="text" id="input" />
<button id="btn">注册</button>
<script>
const input = document.querySelector("#input")
const btn = document.querySelector("#btn")
function checkEmpty() {
if (input.value.length === 0) {
console.log("这里不能为空")
return
}
return "next"
}
function checkNumber() {
if (Number.isNaN(+input.value)) {
console.log("这里必须是数字")
return
}
return "next"
}
function checkLen() {
if (input.value.length < 6) {
console.log("长度必须不小于6")
return
}
return "next"
}
class Chain {
constructor(fn) {
this.checkRules = fn
this.nextRule = null
}
addRule(nextRule) {
this.nextRule = new Chain(nextRule)
return this.nextRule
}
check() {
if (this.checkRules() === "next" && this.nextRule) {
return this.nextRule.check()
}
}
}
const checks = new Chain(checkEmpty)
checks
.addRule(checkNumber)
.addRule(checkLen)
.addRule(() => {
console.log("validation passed")
return "end"
})
btn.onclick = () => checks.check()
</script>
</body>