티스토리 뷰

* 자바스크립트 옵저벼 패턴


document.writeln = function( str ) {
    document.write( str + "<br/>" );
}
function Caps() {
    this.obserable = new Array();
    this.price     = '2000';
}

Caps.prototype = {
    add : function(observer) {
        this.obserable[this.obserable.length] = observer;
    },
    remove : function(observer) {
        for(var i=0;i<this.obserable.length;i++) {
            if(this.obserable[i] == observer) {
                 this.obserable.splice(i,1);
            }
        }
    },
    notify : function(){
        for(var i=0;i<this.obserable.length;i++) {
            this.obserable[i].update(this);
        }
    },
    updatePrice : function(newPrice) {
        this.price = newPrice;
        this.notify();
    },
    getPrice : function(){
        return this.price;
    }
};


function goldStore() {
    this.store = 'goldStore';
}

goldStore.prototype = {
    'update' : function(subject) {
        document.writeln(this.store  + ':' + subject.getPrice());
    }
}

function footStore() {
    this.store = 'footStore';
}

footStore.prototype = {
    'update' : function(subject) {
        document.writeln(this.store  + ':' + subject.getPrice());
    }
}

function familyMart() {
    this.store = 'familyMart';
}

familyMart.prototype =  {
    'update' : function(subject) {
        document.writeln(this.store  + ':' + subject.getPrice());
    }
}

var caps = new Caps();
var goldStore = new goldStore();
var footStore = new footStore();
var familyMart = new familyMart();

caps.add(goldStore);
caps.add(footStore);
caps.add(familyMart);

caps.notify();  //통지


caps.updatePrice('5000'); // 가격 변경 통지

caps.remove(footStore); //remove

caps.notify();
댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 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
글 보관함