javascriptによるデザインパターン
javascriptでデザインパターンを2つ以上使ったプログラムを書けという課題が出た。一応完成したので書いたプログラムを載せておく。
ちなみに今回使用したデザインパターンはIteratorとStrategyの2つ。
プログラムの内容は、配列を作っり、それを選択したソートアルゴリズムを用いてソートして表示するというもの。
アルゴリズムを選択する部分にStrategyパターンを使い、ソートした配列を表示する部分にIteratorパターンを使っている。
参考にしたサイトは私のブックマークのjavascriptのタグを見てください
<html> <head> <script type="text/javascript"> <title>sort</title> <!-- function CreateList() { this.list = new Array(4,12,1,7,10); } CreateList.prototype.getIterator =function() { return new Iterator(this); } function Iterator(of) { this.shelf = of; this.counter = 0; } Iterator.prototype.hasNext = function() { if (this.counter < this.shelf.list.length) { return true; } else { return false; } } Iterator.prototype.next=function() { var value = this.shelf.list[this.counter]; this.counter++; return value; } //Strategyインターフェース function SortStrategy(){ //abstract SortStrategy.prototype.sort = function(){ } } //単純ソート function SimpleSort(){ SimpleSort.prototype.sort = function(list) { var end = list.length - 1; for (var i = 0; i< end; i++){ for (var j = i + 1; j <= end; j++){ if (list[i] > list[j]){ var temp = list[i]; list[i] = list[j]; list[j] = temp; } } } return list; } } SimpleSort.prototype = new SortStrategy(); //選択ソート function SelectSort(){ SelectSort.prototype.sort = function(list) { var end = list.length - 1; for (var i = 0; i < end; i++){ var pos = i; var tmp = list[i]; for (var j = i + 1; j <= end; j++){ if (tmp > list[j]){ pos = j; tmp = list[j]; } } list[pos] = list[i]; list[i] = tmp; } return list; } } SelectSort.prototype = new SelectSort(); function sortStart(){ var selectedValue = document.sort.select.value; var strategy =null; if(selectedValue == 1){ strategy = new SimpleSort(); } if(selectedValue ==2){ strategy = new SelectSort(); } var cl = new CreateList(); cl.list = strategy.sort(cl.list); var hoge = cl.getIterator() while(hoge.hasNext()){ alert(hoge.next()+","); } } //--> </script> </head> <body> <form name ="sort"> <select name="select"> <option value="1">単純ソート</option> <option value="2">選択ソート</option> </select> <input name ="submit" type="button" value="スタート" onClick="sortStart()"/> </form> </body> </html>
おかしなところとかあったらご指摘ください。