javascript 디자인 모드 -- 명령 모드
304876 단어 JavaScript
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title> </title>
5 <meta charset="utf-8">
6 </head>
7 <body>
8
9 <script>
10 /**
11 *
12 *
13 * :
14 * , , , 。
15 *
16 * :
17 *
18 *
19 * 。 。 , 。 , 。 , , (unlimited) (undo) , , 。
20 *
21 * , , , , , , , 。
22 * , , 。 , , , , 。
23 * , , , , Client 。 , , , 。
24 * Invoker 。 , , Invoker 。 , Invoker , 。
25 *
26 *
27 * , , , , , , , , 。
28 *
29 *
30 * , “ ” 。 , , , , , 。
31 * , 。 Invoker 。
32 * ,Client Invoker , , , , 。
33 *
34 *
35 * , , , Command 。
36 * , 。 , , , 。
37 *
38 *
39 * , , Invoker, 。
40 * :
41 * 1. 。
42 * 2. , 。
43 * 3. Invoker 。
44 * 4. Invoker , Invoker 。
45 * :
46 * 1. Invoker , 。
47 * 2. 。
48 * 3. 。
49 *
50 */
51
52 (function () {
53 //
54
55 /**
56 *
57 * @params {Object} receiver
58 */
59 function Command(receiver) {
60 this.receiver = receiver;
61 //
62 this.state = '';
63 }
64
65 Command.prototype.execute = function () {
66 // ,
67 this.receiver.action();
68 };
69
70 //
71 function Receiver() {
72 }
73
74 //
75 Receiver.prototype.action = function () {
76 };
77
78 /**
79 *
80 *
81 */
82 function Invoker() {
83 }
84
85 /**
86 * @params {Object} command
87 */
88 Invoker.prototype.setCommand = function (command) {
89 this.command = command;
90 };
91 //
92 Invoker.prototype.runCommand = function () {
93 this.command.execute();
94 };
95
96 new function Client() {
97 var receiver = new Receiver();
98 var command = new Command(receiver);
99 var invoker = new Invoker();
100 invoker.setCommand(command);
101 invoker.runCommand();
102 }();
103 }());
104
105 /*
106
107
108 。 (execute operation), 。 , execute run 。 , , 。
109
110 , , 。 , (UI)。 。
111 */
112
113 // , start stop
114 // StopAd command class
115 var StopAd = function (adObject) {
116 this.ad = adObject;
117 };
118 StopAd.prototype.execute = function () {
119 this.ad.stop();
120 };
121
122 // StartAd command class
123 var StartAd = function (adObject) {
124 this.ad = adObject;
125 };
126 StartAd.prototype.execute = function () {
127 this.ad.start();
128 };
129 /*
130 , 。 adObject , start stop 。 , 。
131 */
132
133 /*
134 , , :
135 */
136 // implementation code
137 var ads = getAds();
138 for (var i = 0, len = ads.length; i < len; i++) {
139 // Create command objects for starting and stopping the ad
140 var startCommand = new StartAd(ads[i]);
141 var stopCommand = new StopAd(ads[i]);
142
143 // Create the UI elements that will execute the command on click
144 new UIButton('Start ' + ads[i].name, startCommand);
145 new UIButton('stop ' + ads[i].name, stopCommand);
146 }
147 /*
148 UIButton , , 。 , execute 。 。 execute , UIButton。 。
149 */
150
151 /*
152
153
154 。 execute , 。 。 。 execute , 。 this 。
155 */
156
157 // Command using closures
158 function makeSart(adObject) {
159 return function () {
160 adObject.start();
161 };
162 }
163 function makeStop(adObject) {
164 return function () {
165 adObject.stop();
166 };
167 }
168
169 // Implementation code
170 var startCommand = makeStart(ads[0]);
171 var stopCommand = makeStop(ads[0]);
172
173 startCommand();
174 stopCommand();
175 /*
176 ,
177 */
178
179 /*
180 ,
181
182 : (client), (invoking object) (receiving object)。 。 ,for 。 , 。 。 execute , 。 UIButton 。 , execute 。 。 “commandObject.execute()” , “receiver.action()” 。 , start , stop 。
183
184 , , 。
185 , 。
186 */
187
188 //
189 // If no exception is thrown, youcan safely invoke the
190 // execute operation
191 someCommand.execute();
192
193 // ,
194 if (typeof someCommand !== 'function') {
195 throw new Error('Command isn\'t a function');
196 }
197
198
199 //
200 /*
201 ( start stop ) ( ) 。 , 。 , :
202 */
203 // SimpleCommand, a loosely coupled, simple command class.
204 var SimpleCommand = function (receiver) {
205 this.receiver = receiver;
206 };
207 SimpleCommand.prototype.execute = function () {
208 this.receiver.action();
209 };
210
211 /*
212 。 , 。 , :
213 */
214 // ComplexCommand, a tightly coupled, complex command class.
215 var ComplexCommand = function () {
216 this.logger = new Logger();
217 this.xhrHandler = XhrManager.createXhrHandler();
218 this.parameters = {};
219 };
220 ComplexCommand.prototype = {
221 setParameter: function (key, value) {
222 this.parameters[key] = value;
223 },
224 execute: function () {
225 this.logger.log('Executing command');
226 var postArray = [];
227 for (var key in this.parameters) {
228 if (this.parameters.hasOwnProperty(key)) {
229 postArray.push(key + '=' + this.parameters[key]);
230 }
231 }
232 var postString = postArray.join('&');
233 this.xhrHandler.request(
234 'POST',
235 'script.php',
236 function () {
237 },
238 postString
239 );
240 }
241 };
242
243 /*
244 , execute 。 :
245 */
246 // GreyAreaCommand, somewhere between simple and complex
247 var GreyAreaCommand = function (receiver) {
248 this.logger = new Logger();
249 this.receiver = receiver;
250 };
251 GreyAreaCommand.prototype.execute = function () {
252 this.logger.log('Executing command');
253 this.receiver.prepareAction();
254 this.receiver.action();
255 };
256
257 /*
258 ( ) , 。
259 */
260
261 // :
262 //
263 /*
264 Menubar,Menu MenuItem , , , ,Menubar Menu , MenuItem 。Menubar Menu :
265 */
266 // MenuBar class, a composite
267 var MenuBar = function () {
268 this.menus = {};
269 this.element = document.createElement('ul');
270 this.element.style.display = 'none';
271 };
272 MenuBar.prototype = {
273 add: function (menuObject) {
274 this.menus[menuObject.name] = menuObject;
275 this.element.appendChild(this.menus[menuObject.name].getElement());
276 },
277 remove: function (name) {
278 delete this.menus[name];
279 },
280 getChild: function (name) {
281 return this.menus[name];
282 },
283 getElement: function () {
284 return this.element;
285 },
286 show: function () {
287 this.element.style.display = '';
288 for (var name in this.menus) {
289 this.menus[name].show();
290 }
291 }
292 };
293
294 // Menu class, a composite
295 var Menu = function (name) {
296 this.name = name;
297 this.items = {};
298 this.element = document.createElement('li');
299 this.element.style.display = 'none';
300 this.container = document.createElement('ul');
301 this.element.appendChild(this.container);
302 };
303 Menu.prototype = {
304 add: function (menuItemObject) {
305 this.items[menuItemObject.name] = menuItemObject;
306 this.container.appendChild(this.items[menuItemObject.name].getElement());
307 },
308 remove: function () {
309 delete this.items[name];
310 },
311 getChild: function (name) {
312 return this.items[name];
313 },
314 getElement: function () {
315 return this.element;
316 },
317 show: function () {
318 this.element.style.display = '';
319 for (var name in this.items) {
320 this.items[name].show();
321 }
322 }
323 };
324
325 //
326 // MenuItem class, a leaf
327 var MenuItem = function (name, command) {
328 this.name = name;
329 this.element = document.createElement('li');
330 this.element.style.display = 'none';
331 this.anchor = document.createElement('a');
332 this.anchor.href = '#';
333 this.element.appendChild(this.anchor);
334 this.anchor.innerHTML = this.name;
335
336 addEvent(this.anchor, 'click', function (e) {
337 e = e || window.event;
338 if (typeof e.preventDefault === 'function') {
339 e.preventDefault();
340 } else {
341 e.returnValue = false;
342 }
343 command.execute();
344 });
345 };
346 MenuItem.prototype = {
347 add: function () {
348 },
349 remove: function () {
350 },
351 getChild: function () {
352 },
353 getElement: function () {
354 return this.element;
355 },
356 show: function () {
357 this.element.style.display = '';
358 }
359 };
360
361 //
362 // MenuCommand class, a command object
363 var MenuCommand = function (action) {
364 this.action = action;
365 };
366 MenuCommand.prototype.execute = function () {
367 this.action.action();
368 };
369
370
371 // Receiver objects, instantiated from existing classes
372 var Test1 = function () {
373 console.log('test1');
374 };
375 Test1.prototype = {
376 action: function () {
377 console.log('this is test1 fn1');
378 }
379 };
380 var Test2 = function () {
381 console.log('test2');
382 };
383 Test2.prototype = {
384 action: function () {
385 console.log('this is test2 fn1');
386 }
387 };
388 var Test3 = function () {
389 console.log('test3');
390 };
391 var test1 = new Test1();
392 var test2 = new Test2();
393 var test3 = new Test3();
394
395 // Create the menu bar
396 var appMenuBar = new MenuBar();
397
398 // The File menu
399 var fileMenu = new Menu('File');
400
401 var test1Command1 = new MenuCommand(test1);
402
403 fileMenu.add(new MenuItem('test1-1', test1Command1));
404
405 appMenuBar.add(fileMenu);
406
407 var insertMenu = new Menu('Insert');
408 var test2Command2 = new MenuCommand(test2);
409 insertMenu.add(new MenuItem('test2-1', test2Command2));
410
411 appMenuBar.add(insertMenu);
412
413 document.body.appendChild(appMenuBar.getElement());
414 appMenuBar.show();
415
416
417 (function () {
418 //
419
420 //
421
422 // ReversibleCommand interface
423 var ReversibleCommand = new Interface('ReversibleCommand', ['execute', 'undo']);
424
425 // 4 ,
426 // :
427 var MoveUp = function (cursor) {
428 this.cursor = cursor;
429 };
430 MoveUp.prototype = {
431 execute: function () {
432 this.cursor.move(0, -10);
433 },
434 undo: function () {
435 this.cursor.move(0, 10);
436 }
437 };
438
439 var MoveDown = function (cursor) {
440 this.cursor = cursor;
441 };
442 MoveDown.prototype = {
443 execute: function () {
444 this.cursor.move(0, 10);
445 },
446 undo: function () {
447 this.cursor.move(0, -10);
448 }
449 };
450
451 var MoveLeft = function (cursor) {
452 this.cursor = cursor;
453 };
454 MoveLeft.prototype = {
455 execute: function () {
456 this.cursor.move(-10, 0);
457 },
458 undo: function () {
459 this.cursor.move(10, 0);
460 }
461 };
462
463 var MoveRight = function (cursor) {
464 this.cursor = cursor;
465 };
466 MoveRight.prototype = {
467 execute: function () {
468 this.cursor.move(10, 0);
469 },
470 undo: function () {
471 this.cursor.move(-10, 0);
472 }
473 };
474
475 // ,
476 // Cursor class
477 var Cursor = function (width, height, parent) {
478 this.width = width;
479 this.height = height;
480 this.position = {
481 x: width / 2,
482 y: height / 2
483 };
484
485 this.canvas = document.createElement('canvas');
486 this.canvas.width = this.width;
487 this.canvas.height = this.height;
488 parent.appendChild(this.canvas);
489
490 this.ctx = this.canvas.getContext('2d');
491 this.ctx.fillStyle = '#cc0000';
492 this.move(0, 0);
493 };
494 Cursor.prototype.move = function (x, y) {
495 this.position.x += x;
496 this.position.y += y;
497
498 this.ctx.clearRect(0, 0, this.width, this.height);
499 this.ctx.fillRect(this.position.x, this.position.y, 3, 3);
500 };
501
502 //
503 // UndoDecorator class
504 var UndoDecorator = function (command, undoStack) {
505 this.command = command;
506 this.undoStack = undoStack;
507 };
508 UndoDecorator.prototype = {
509 execute: function () {
510 this.undoStack.push(this.command);
511 this.command.execute();
512 },
513 undo: function () {
514 this.command.undo();
515 }
516 };
517
518 // , HTML , click ,
519 // execute undo :
520 // CommandButton class
521 var CommandButton = function (label, command, parent) {
522 this.element = document.createElement('button');
523 this.element.innerHTML = label;
524 parent.appendChild(this.element);
525
526 addEvent(this.element, 'click', function () {
527 command.execute();
528 });
529 };
530
531 // UndoButton class
532 var UndoButton = function (label, parent, undoStack) {
533 this.element = document.createElement('button');
534 this.element.innerHTML = label;
535 parent.appendChild(this.element);
536
537 addEvent(this.element, 'click', function () {
538 if (undoStack.length === 0) return;
539 var lastCommand = undoStack.pop();
540 lastCommand.undo();
541 });
542 };
543 /*
544 UndoDecorator ,UndoButton 。 。 UndoDecorator execute 。 , undo 。 。
545 */
546
547 // Implementation code
548 var body = document.body;
549 var cursor = new Cursor(400, 400, body);
550 var undoStack = [];
551
552 var upCommand = new UndoDecorator(new MoveUp(cursor), undoStack);
553 var downCommand = new UndoDecorator(new MoveDown(cursor), undoStack);
554 var leftCommand = new UndoDecorator(new MoveLeft(cursor), undoStack);
555 var rightCommand = new UndoDecorator(new MoveRight(cursor), undoStack);
556
557 var upButton = new CommandButton('Up', upCommand, body);
558 var downButton = new CommandButton('Down', downCommand, body);
559 var leftButton = new CommandButton('Left', leftCommand, body);
560 var rightButton = new CommandButton('Right', rightCommand, body);
561 var undoButton = new UndoButton('Undo', body, undoStack);
562 }());
563
564
565 (function () {
566 //
567 /*
568 , 。 , 。 A B , B A , 。
569
570 , ( ) 。 , 。 , , 。
571 */
572
573 // Movement commands
574 var MoveUp = function (cursor) {
575 this.cursor = cursor;
576 };
577 MoveUp.prototype = {
578 execute: function () {
579 this.cursor.move(0, -10);
580 }
581 };
582
583 var MoveDown = function (cursor) {
584 this.cursor = cursor;
585 };
586 MoveDown.prototype = {
587 execute: function () {
588 this.cursor.move(0, 10);
589 }
590 };
591
592 var MoveLeft = function (cursor) {
593 this.cursor = cursor;
594 };
595 MoveLeft.prototype = {
596 execute: function () {
597 this.cursor.move(-10, 0);
598 }
599 };
600
601 var MoveRight = function (cursor) {
602 this.cursor = cursor;
603 };
604 MoveRight.prototype = {
605 execute: function () {
606 this.cursor.move(10, 0);
607 }
608 };
609
610 // Cursor class, with an internal command stack
611 var Cursor = function (width, height, parent) {
612 this.width = width;
613 this.height = height;
614 this.commandStack = [];
615
616 this.canvas = document.createElement('canvas');
617 this.canvas.width = this.width;
618 this.canvas.height = this.height;
619 parent.appendChild(this.canvas);
620
621 this.ctx = this.canvas.getContext('2d');
622 this.ctx.strokeStyle = '#cc0000';
623 this.move(0, 0);
624 };
625 Cursor.prototype = {
626 move: function (x, y) {
627 var that = this;
628 this.commandStack.push(function () {
629 that.lineTo(x, y);
630 });
631 this.executeCommands();
632 },
633 lineTo: function (x, y) {
634 this.position.x += x;
635 this.position.y += y;
636 this.ctx.lineTo(this.position.x, this.position.y);
637 },
638 executeCommands: function () {
639 this.position = {
640 x: this.width / 2,
641 y: this.height / 2
642 };
643 this.ctx.clearRect(0, 0, this.width, this.height);
644 this.ctx.beginPath();
645 this.ctx.moveTo(this.position.x, this.position.y);
646 for (var i = 0, len = this.commandStack.length; i < len; i++) {
647 this.commandStack[i]();
648 }
649 this.ctx.stroke();
650 },
651 undo: function () {
652 this.commandStack.pop();
653 this.executeCommands();
654 }
655 };
656
657 // UndoButton class
658 var UndoButton = function (label, parent, cursor) {
659 this.element = document.createElement('button');
660 this.element.innerHTML = label;
661 parent.appendChild(this.element);
662 addEvent(this.element, 'click', function () {
663 cursor.undo();
664 });
665 };
666 // CommandButton class
667 var CommandButton = function (label, command, parent) {
668 this.element = document.createElement('button');
669 this.element.innerHTML = label;
670 parent.appendChild(this.element);
671
672 addEvent(this.element, 'click', function () {
673 command.execute();
674 });
675 };
676
677 var body = document.body;
678 var cursor = new Cursor(400, 400, body);
679
680 var upCommand = new MoveUp(cursor);
681 var downCommand = new MoveDown(cursor);
682 var leftCommand = new MoveLeft(cursor);
683 var rightCommand = new MoveRight(cursor);
684
685 var upButton = new CommandButton('Up', upCommand, body);
686 var downButton = new CommandButton('Down', downCommand, body);
687 var leftButton = new CommandButton('Left', leftCommand, body);
688 var rightButton = new CommandButton('Right', rightCommand, body);
689 var undoButton = new UndoButton('Undo', body, cursor);
690 }());
691
692 (function () {
693 //
694 /*
695 。
696
697 : , 。
698 : 。
699 : , , , 。
700 , : 。
701
702
703 */
704
705 //
706 var HotCook = function () {
707 };
708 HotCook.prototype = {
709 cook: function (name) {
710 console.log(' :' + name);
711 }
712 };
713
714 //
715 var CoolCook = function () {
716 };
717 CoolCook.prototype = {
718 cook: function (name) {
719 console.log(' ' + name + ' , 。');
720 }
721 }
722
723 // ,
724
725 var DuckCommand = function () {
726 this.cookApi = null;
727 };
728 DuckCommand.prototype = {
729 constructor: DuckCommand,
730 setCookApi: function (cookApi) {
731 this.cookApi = cookApi;
732 },
733 execute: function () {
734 this.cookApi.cook(' ');
735 }
736 };
737
738 var ChopCommand = function () {
739 this.cookApi = null;
740 };
741 ChopCommand.prototype = {
742 constructor: ChopCommand,
743 setCookApi: function (cookApi) {
744 this.cookApi = cookApi;
745 },
746 execute: function () {
747 this.cookApi.cook(' ');
748 }
749 };
750
751 var PorkCommand = function () {
752 this.cookApi = null;
753 };
754 PorkCommand.prototype = {
755 constructor: PorkCommand,
756 setCookApi: function (cookApi) {
757 this.cookApi = cookApi;
758 },
759 execute: function () {
760 this.cookApi.cook(' ');
761 }
762 };
763
764 // ,
765 var MenuCommand = function () {
766 var col = [];
767
768 this.addCommand = function (cmd) {
769 col.push(cmd);
770 };
771
772 this.execute = function () {
773 for (var i = 0 , len = col.length; i < len; i++) {
774 col[i].execute();
775 }
776 };
777 };
778
779 // , , 。
780 var Waiter = function () {
781 var menuCommand = new MenuCommand();
782
783 //
784 this.orderDish = function (cmd) {
785 var hotCook = new HotCook();
786 var coolCook = new CoolCook();
787
788 if (cmd instanceof DuckCommand) {
789 cmd.setCookApi(hotCook);
790 } else if (cmd instanceof ChopCommand) {
791 cmd.setCookApi(hotCook);
792 } else if (cmd instanceof PorkCommand) {
793 cmd.setCookApi(coolCook);
794 }
795
796 menuCommand.addCommand(cmd);
797 };
798
799 //
800 this.orderOver = function () {
801 menuCommand.execute();
802 };
803 };
804
805 var waiter = new Waiter();
806 var chop = new ChopCommand();
807 var duck = new DuckCommand();
808 var pork = new PorkCommand();
809
810 waiter.orderDish(chop);
811 waiter.orderDish(duck);
812 waiter.orderDish(pork);
813
814 waiter.orderOver();
815
816 }());
817
818 (function () {
819 //
820
821 function createCommand(name) {
822 function Command(tableNum) {
823 this.cookApi = null;
824 this.tableNum = tableNum;
825 }
826
827 Command.prototype = {
828 setCookApi: function (cookApi) {
829 this.cookApi = cookApi;
830 },
831 execute: function () {
832 this.cookApi.cook(this.tableNum, name);
833 }
834 };
835
836 return Command;
837 }
838
839 var ChopCommand = createCommand(' ');
840 var DuckCommand = createCommand(' ');
841
842 var CommandQueue = {
843 cmds: [],
844 addMenu: function (menu) {
845 var cmds = menu.getCommands();
846 for (var i = 0, len = cmds.length; i < len; i++) {
847 this.cmds.push(cmds[i]);
848 }
849 },
850 getOneCommand: function () {
851 return this.cmds.length ? this.cmds.shift() : null;
852 }
853 };
854
855 var MenuCommand = function () {
856 this.col = [];
857 };
858 MenuCommand.prototype = {
859 addCommand: function (cmd) {
860 this.col.push(cmd);
861 },
862 setCookApi: function (cookApi) {
863 },
864 getTableNum: function () {
865 return 0;
866 },
867 getCommands: function () {
868 return this.col;
869 },
870 execute: function () {
871 CommandQueue.addMenu(this);
872 }
873 };
874
875 var HotCook = function (name) {
876 this.name = name;
877 };
878 HotCook.prototype = {
879 cook: function (tableNum, name) {
880 var cookTime = parseInt(10 * Math.random() + 3);
881 console.log(this.name + ' ' + tableNum + ' :' + name);
882
883 var me = this;
884 setTimeout(function () {
885 console.log(me.name + ' ' + tableNum + ' :' + name + ', =' + cookTime + ' ');
886 }, cookTime * 1000);
887 },
888 run: function () {
889 var me = this;
890 setTimeout(function () {
891 var cmd;
892
893 while ((cmd = CommandQueue.getOneCommand())) {
894 cmd.setCookApi(me);
895 cmd.execute();
896 }
897 }, 1000);
898 }
899 };
900
901 var Waiter = function () {
902 this.menuCommand = new MenuCommand();
903 };
904 Waiter.prototype = {
905 orderDish: function (cmd) {
906 this.menuCommand.addCommand(cmd);
907 },
908 orderOver: function () {
909 this.menuCommand.execute();
910 }
911 };
912
913 var c1 = new HotCook(' ');
914 c1.run();
915
916 for (var i = 0; i < 5; i++) {
917 var waiter = new Waiter();
918 var chop = new ChopCommand(i);
919 var duck = new DuckCommand(i);
920
921 waiter.orderDish(chop);
922 waiter.orderDish(duck);
923
924 waiter.orderOver();
925 }
926
927 }());
928
929 function test() {
930 //
931 // TODO ,
932 // ,
933 var fs = require('fs');
934 var Promise = require('d:\
ode\
ode_modules\\rsvp');
935
936 var FileOpeUtil = {
937 readFile: function (pathName) {
938 var def = Promise.defer();
939
940 fs.open(pathName, 'r', function opened(err, fd) {
941 if (err) {
942 def.reject();
943 fs.close(fd);
944 throw err;
945 }
946
947 var readBuffer = new Buffer(1024);
948 var bufferOffset = 0;
949 var bufferLength = readBuffer.length;
950 var filePosition = null;
951
952 fs.read(
953 fd,
954 readBuffer,
955 bufferOffset,
956 bufferLength,
957 filePosition,
958 function read(err, readBytes) {
959 if (err) {
960 def.reject(err);
961 fs.close(fd);
962 return;
963 }
964
965 if (readBytes >= 0) {
966 try {
967 def.resolve(JSON.parse(readBuffer.slice(0, readBytes).toString('utf8')));
968 } catch (e) {
969 def.reject(e);
970 }
971
972 fs.close(fd);
973 }
974 }
975 );
976 });
977
978 return def.promise;
979 },
980 writeFile: function (pathName, list) {
981 var def = Promise.defer();
982
983 fs.open(pathName, 'w', function opened(err, fd) {
984 if (err) {
985 def.reject();
986 fs.close(fd);
987 throw err;
988 }
989
990 var writeBuffer = new Buffer(JSON.stringify(list));
991 var bufferPosition = 0;
992 var bufferLength = writeBuffer.length;
993 var filePosition = null;
994
995 fs.write(
996 fd,
997 writeBuffer,
998 bufferPosition,
999 bufferLength,
1000 filePosition,
1001 function wrote(err, written) {
1002 if (err) {
1003 def.reject(err);
1004 fs.close(fd);
1005 return;
1006 }
1007
1008 console.log('wrote ' + written + ' bytes');
1009 def.resolve(written);
1010 fs.close(fd);
1011 }
1012 );
1013 });
1014
1015 return def.promise;
1016 }
1017 };
1018
1019 function createCommand(name) {
1020 function Command(tableNum) {
1021 this.cookApi = null;
1022 this.tableNum = tableNum;
1023 }
1024
1025 Command.prototype = {
1026 setCookApi: function (cookApi) {
1027 this.cookApi = cookApi;
1028 },
1029 execute: function () {
1030 this.cookApi.cook(this.tableNum, name);
1031 }
1032 };
1033
1034 return Command;
1035 }
1036
1037 var ChopCommand = createCommand(' ');
1038 var DuckCommand = createCommand(' ');
1039
1040 var MenuCommand = function () {
1041 this.col = [];
1042 };
1043 MenuCommand.prototype = {
1044 addCommand: function (cmd) {
1045 this.col.push(cmd);
1046 },
1047 setCookApi: function (cookApi) {
1048 },
1049 getTableNum: function () {
1050 return 0;
1051 },
1052 getCommands: function () {
1053 return this.col;
1054 },
1055 execute: function () {
1056 CommandQueue.addMenu(this);
1057 }
1058 };
1059
1060 var HotCook = function (name) {
1061 this.name = name;
1062 };
1063 HotCook.prototype = {
1064 cook: function (tableNum, name) {
1065 var cookTime = parseInt(10 * Math.random() + 3);
1066 console.log(this.name + ' ' + tableNum + ' :' + name);
1067
1068 var me = this;
1069 setTimeout(function () {
1070 console.log(me.name + ' ' + tableNum + ' :' + name + ', =' + cookTime + ' ');
1071 }, cookTime * 1000);
1072 },
1073 run: function () {
1074 var me = this;
1075 setTimeout(function () {
1076 var cmd;
1077
1078 while ((cmd = CommandQueue.getOneCommand())) {
1079 cmd.setCookApi(me);
1080 cmd.execute();
1081 break;
1082 }
1083 }, 1000);
1084 }
1085 };
1086
1087 var Waiter = function () {
1088 this.menuCommand = new MenuCommand();
1089 };
1090 Waiter.prototype = {
1091 orderDish: function (cmd) {
1092 this.menuCommand.addCommand(cmd);
1093 },
1094 orderOver: function () {
1095 this.menuCommand.execute();
1096 }
1097 };
1098
1099
1100 var CommandQueue = {
1101 cmds: [],
1102 addMenu: function (menu) {
1103 var cmds = menu.getCommands();
1104 for (var i = 0, len = cmds.length; i < len; i++) {
1105 this.cmds.push(cmds[i]);
1106 }
1107 FileOpeUtil.writeFile('./test.txt', this.cmds);
1108 },
1109 getOneCommand: function () {
1110 var cmd = null;
1111
1112 if (this.cmds.length) {
1113 cmd = this.cmds.shift();
1114 FileOpeUtil.writeFile('./test.txt', this.cmds);
1115 }
1116
1117 return cmd;
1118 }
1119 };
1120
1121 var FILE_NAME = './test.txt';
1122
1123 FileOpeUtil.readFile(FILE_NAME)
1124 .then(function (data) {
1125 console.log(data);
1126 data.map(function () {
1127
1128 });
1129
1130 CommandQueue.cmds = data;
1131 main();
1132 }, function () {
1133 main();
1134 });
1135
1136 function main() {
1137 var c1 = new HotCook(' ');
1138 c1.run();
1139
1140 for (var i = 0; i < 5; i++) {
1141 var waiter = new Waiter();
1142 var chop = new ChopCommand(i);
1143 var duck = new DuckCommand(i);
1144
1145 waiter.orderDish(chop);
1146 waiter.orderDish(duck);
1147
1148 waiter.orderOver();
1149 }
1150 }
1151 }
1152
1153 /*
1154
1155
1156 。 , XHR 。 , 。 , 。 , 。 , , 。
1157 */
1158
1159 /*
1160
1161
1162 1. , , 。 , 。
1163 2. , 。 , 。
1164 3. , , , 。
1165 4. , 。 , , , , 。
1166 5. , 。
1167
1168
1169
1170
1171 1.
1172 -- , -- , , 。
1173 2.
1174 , , , 。
1175 3.
1176 , 。
1177 4.
1178
1179
1180
1181
1182
1183 , , 。 , , 。 , 。
1184
1185
1186
1187
1188
1189
1190 。
1191
1192
1193
1194 , , , 。
1195
1196
1197 , 。
1198 */
1199
1200
1201 /* Title: Command
1202 Description: creates objects which encapsulate actions and parameters
1203 */
1204
1205 (function () {
1206
1207 var CarManager = {
1208
1209 /* request information */
1210 requestInfo: function (model, id) {
1211 return 'The purchase info for ' + model + ' with ID ' + id + ' is being processed...';
1212 },
1213
1214 /* purchase the car */
1215 buyVehicle: function (model, id) {
1216 return 'You have successfully purchased Item ' + id + ', a ' + model + '.';
1217 }
1218
1219 };
1220
1221 CarManager.execute = function (commad) {
1222 return CarManager[commad.request](commad.model, commad.carID);
1223 };
1224
1225 var actionA = CarManager.execute({request: 'requestInfo', model: 'Ford Mondeo', carID: '543434'});
1226 console.log(actionA);
1227 var actionB = CarManager.execute({request: 'buyVehicle', model: 'Ford Mondeo', carID: '543434'});
1228 console.log(actionB);
1229
1230 })();
1231
1232
1233 // http://www.joezimjs.com/javascript/javascript-design-patterns-command/
1234 var EnableAlarm = function (alarm) {
1235 this.alarm = alarm;
1236 }
1237 EnableAlarm.prototype.execute = function () {
1238 this.alarm.enable();
1239 }
1240
1241 var DisableAlarm = function (alarm) {
1242 this.alarm = alarm;
1243 }
1244 DisableAlarm.prototype.execute = function () {
1245 this.alarm.disable();
1246 }
1247
1248 var ResetAlarm = function (alarm) {
1249 this.alarm = alarm;
1250 }
1251 ResetAlarm.prototype.execute = function () {
1252 this.alarm.reset();
1253 }
1254
1255 var SetAlarm = function (alarm) {
1256 this.alarm = alarm;
1257 }
1258 SetAlarm.prototype.execute = function () {
1259 this.alarm.set();
1260 }
1261
1262 var alarms = [/* array of alarms */],
1263 i = 0, len = alarms.length;
1264
1265 for (; i < len; i++) {
1266 var enable_alarm = new EnableAlarm(alarms[i]),
1267 disable_alarm = new DisableAlarm(alarms[i]),
1268 reset_alarm = new ResetAlarm(alarms[i]),
1269 set_alarm = new SetAlarm(alarms[i]);
1270
1271 new Button('enable', enable_alarm);
1272 new Button('disable', disable_alarm);
1273 new Button('reset', reset_alarm);
1274 new Button('set', set_alarm);
1275 }
1276
1277
1278 var makeEnableCommand = function (alarm) {
1279 return function () {
1280 alarm.enable();
1281 }
1282 }
1283
1284 var makeDisableCommand = function (alarm) {
1285 return function () {
1286 alarm.disable();
1287 }
1288 }
1289
1290 var makeResetCommand = function (alarm) {
1291 return function () {
1292 alarm.reset();
1293 }
1294 }
1295
1296 var makeSetCommand = function (alarm) {
1297 return function () {
1298 alarm.set();
1299 }
1300 }
1301
1302 </script>
1303 </body>
1304 </html>
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
기초 정리 - 1문자 (String) 숫자 (Number) 불린 (Boolean) null undefined 심볼 (Symbol) 큰정수 (BigInt) 따옴표로 묶어 있어야 함 Not-A-Number - 숫자 데이터 / 숫자로 표...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.