什么是命令模式
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。
调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
命令模式最常见的应用场景是:有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么。此时希望用一种松耦合的方式来设计程序,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。
面向对象例子:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 
 | class RenderLogin{constructor() {
 this.login = document.createElement('div');
 this.options = {
 width: '100px',
 height: '100px',
 border: '1px solid red'
 }
 }
 
 render(options) {
 this.options = {...this.options, ...options};
 for (let key of Object.keys(this.options)) {
 this.login.style[key] = this.options[key];
 }
 document.body.appendChild(this.login);
 }
 
 remove() {
 document.body.removeChild(this.login);
 }
 }
 
 class RenderLoginCommand{
 constructor() {
 this.renderLogin = new RenderLogin();
 }
 
 excute(reciever) {
 this.renderLogin.render(reciever.options);
 }
 
 undo() {
 this.renderLogin.remove();
 }
 }
 
 export class LoginButton{
 constructor() {
 this.options = {
 background: 'grey',
 borderRadius: '50%'
 }
 this.renderLoginCommand = new RenderLoginCommand();
 }
 }
 
 |