JS设计模式-命令模式
2022/2/6 23:12:46
本文主要是介绍JS设计模式-命令模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
JS设计模式-命令模式
1.面向对象模式
看以下代码,用面向对象的方式实现命令模式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id = 'button1'>button1</button> <button id = 'button2'>button1</button> <button id = 'button3'>button1</button> </body> <script> var mainMenu = { refreshMainMenu:function(){ console.log("refreshMainMenu"); } } var subMenu = { addItem:function(){ console.log('addItem') }, delItem:function(){ console.log('delItem'); } } function setCommand(button,command){ button.onclick = function(){ command.execute() } } function RefreshMainMenu(receiver){ this.receiver = receiver } RefreshMainMenu.prototype.execute = function(){ this.receiver.refreshMainMenu() } function AddItem(receiver){ this.receiver = receiver } AddItem.prototype.execute = function(){ this.receiver.addItem() } function DelItem(receiver){ this.receiver = receiver } DelItem.prototype.execute = function(){ this.receiver.delItem() } var refresh = new RefreshMainMenu(mainMenu) var add = new AddItem(subMenu) var del = new DelItem(subMenu) setCommand(button1,refresh) setCommand(button2,add) setCommand(button3,del) </script> </html>
通过统一的接口execute来执行命令
2.其他模式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id = 'button1'>button1</button> <button id = 'button2'>button1</button> <button id = 'button3'>button1</button> </body> <script> var mainMenu = { refreshMainMenu:function(){ console.log("refreshMainMenu"); } } var subMenu = { addItem:function(){ console.log('addItem') }, delItem:function(){ console.log('delItem'); } } function setCommand(button,command){ button.onclick = function(){ command.execute() } } function RefreshMainMenu(receiver){ return { execute:function(){ receiver.refreshMainMenu() } } } function AddItem(receiver){ return { execute:function(){ receiver.addItem() } } } function DelItem(receiver){ return { execute:function(){ receiver.delItem() } } } var refresh = RefreshMainMenu(mainMenu) var add = AddItem(subMenu) var del = DelItem(subMenu) setCommand(button1,refresh) setCommand(button2,add) setCommand(button3,del) </script> </html>
通过闭包的形式实现
这篇关于JS设计模式-命令模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-04React 19 来了!新的编译器简直太棒了!
- 2025-01-032025年Node.js与PHP大比拼:挑选最适合的后端技术进行现代web开发
- 2025-01-03?? 用 Gemini API、Next.js 和 TailwindCSS 快速搭建 AI 推文生成项目 ??
- 2024-12-31Vue CLI多环境配置学习入门
- 2024-12-31Vue CLI学习入门:一步一步搭建你的第一个Vue项目
- 2024-12-31Vue3公共组件学习入门:从零开始搭建实用组件库
- 2024-12-31Vue3公共组件学习入门教程
- 2024-12-31Vue3学习入门:新手必读教程
- 2024-12-31Vue3学习入门:初学者必备指南
- 2024-12-30Vue CLI多环境配置教程:轻松入门指南