본문 바로가기

Web/JavaScript

[Design Pattern) 5.Command Pattern

728x90

https://www.dofactory.com/javascript/design-patterns/command

 

JavaScript Command Design Pattern

JavaScript Command The Command pattern encapsulates actions as objects. Command objects allow for loosely coupled systems by separating the objects that issue a request from the objects that actually process the request. These requests are called events an

www.dofactory.com

 

function add(x, y) { return x + y; }
function sub(x, y) { return x - y; }
function mul(x, y) { return x * y; }
function div(x, y) { return x / y; }

var Command = function (execute, undo, value) {
    this.execute = execute;
    this.undo = undo;
    this.value = value;
}

var AddCommand = function (value) {
    return new Command(add, sub, value);
};

var SubCommand = function (value) {
    return new Command(sub, add, value);
};

var MulCommand = function (value) {
    return new Command(mul, div, value);
};

var DivCommand = function (value) {
    return new Command(div, mul, value);
};

var Calculator = function () {
    var current = 0;
    var commands = [];

    function action(command) {
        var name = command.execute.toString().substr(9, 3);
        return name.charAt(0).toUpperCase() + name.slice(1);
    }

    return {
        execute: function (command) {
            current = command.execute(current, command.value);
            commands.push(command);
            console.log(action(command) + ": " + command.value);
        },

        undo: function () {
            var command = commands.pop();
            current = command.undo(current, command.value);
            console.log("Undo " + action(command) + ": " + command.value);
        },

        getCurrentValue: function () {
            return current;
        }
    }
}

function run() {

    var calculator = new Calculator();

    // issue commands

    calculator.execute(new AddCommand(100));
    calculator.execute(new SubCommand(24));
    calculator.execute(new MulCommand(6));
    calculator.execute(new DivCommand(2));

    // reverse last two commands

    calculator.undo();
    calculator.undo();

    console.log("\nValue: " + calculator.getCurrentValue());
}

 

https://www.youtube.com/watch?v=r601hDellMs&list=PL3xNAKVIm80JldJ6IZBx5eQxck5JA6VuV&index=5

명령을 캡슐화 하여 처리함

-> 명령/수신자/발동자/클라이언트

 

 

 

 

 

 

 

 

 

 

 

728x90

'Web > JavaScript' 카테고리의 다른 글

[Design Pattern] 7.Prototype Pattern  (0) 2023.11.17
[Design Pattern] 6. Decorator Pattern  (0) 2023.11.16
[Design Pattern] 4. Facade Pattern  (0) 2023.11.13
[Design Pattern] 3.Observer Pattern  (0) 2023.11.12
[Design Pattern] 2. factory pattern  (0) 2023.11.11