package com.example.studytest;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class ObserverSample extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Calculater cal = new Calculater();
cal.add(new AllObserver());
cal.add(new HighObserver());
cal.plus(5);
cal.minus(2);
cal.plus(15);
}
interface Observer {
abstract void update(Calculater action);
}
class AllObserver implements Observer {
public void update(Calculater cal) {
// TODO Auto-generated method stub
Log.d("test", "ALL : " + String.valueOf(cal.getResult()));
}
}
class HighObserver implements Observer {
public void update(Calculater cal) {
// TODO Auto-generated method stub
if (cal.getResult() > 10) {
Log.d("test", "High : " + String.valueOf(cal.getResult()));
}
}
}
class Calculater {
ArrayList<Observer> observers = new ArrayList<Observer>();
int i = 0;
void add(Observer ob) {
observers.add(ob);
}
void remover(Observer ob) {
observers.remove(ob);
}
void notifys() {
Iterator<Observer> it = observers.iterator();
while (it.hasNext()) {
Observer o = it.next();
o.update(this);
}
}
int getResult() {
return i;
}
void minus(int n) {
i-=n;
}
void plus(int n) {
i+=n;
}
}
}
'Program > 디자인패턴' 카테고리의 다른 글
FacadeSample (0) | 2012.09.05 |
---|---|
FlyweightSample (0) | 2012.09.05 |
ProxySample (0) | 2012.09.05 |
디자인패턴 스터디 1주차 - 추상팩토리,빌더,팩토리메소드 (0) | 2012.08.22 |