http://www.books.com.tw/products/0010750585
觀察者模式 Observer
目的:處理一個物件對應多個物件之間的連動關係
package com.ssc24.chap08.demo01;
public abstract class Adventurer {
protected String name;
public Adventurer(String name) {
this.name = name;
}
public abstract void getQuestions(String questions);
}
package com.ssc24.chap08.demo01;
public class Association extends Subject {
@Override
public void sendQuestions(String questions) {
for (Adventurer adventurer : list) {
adventurer.getQuestions(questions);
}
}
}
package com.ssc24.chap08.demo01;
public class Bard extends Adventurer {
public Bard(String name) {
super(name);
}
@Override
public void getQuestions(String questions) {
if (questions.length() > 10) {
System.out.println(this.name + ":任務太難了,我只會唱歌跳舞,不接不接");
} else {
System.out.println(this.name + ":當街頭藝人太難賺了,偶爾也要解任務賺點錢的");
}
}
}
package com.ssc24.chap08.demo01;
public class Gunman extends Adventurer {
public Gunman(String name) {
super(name);
}
@Override
public void getQuestions(String questions) {
if (questions.length() < 10) {
System.out.println(this.name + ":任務太簡單了,我不想理他");
} else {
System.out.println(this.name + ":只要我的手上有槍,誰都殺不死我,出發執行任務賺獎金啦!!!");
}
}
}
package com.ssc24.chap08.demo01;
public class Lancer extends Adventurer {
public Lancer(String name) {
super(name);
}
@Override
public void getQuestions(String questions) {
System.out.println(this.name + " :單來就改,任務來就接,沒在怕的");
}
}
package com.ssc24.chap08.demo01;
import java.util.ArrayList;
import java.util.List;
public abstract class Subject {
protected List<Adventurer> list = new ArrayList<Adventurer>();
public void add(Adventurer observer) {
list.add(observer);
}
public void remove(Adventurer observer){
list.remove(observer);
}
public abstract void sendQuestions(String question);
}
package com.ssc24.chap08.demo01;
import static org.junit.Assert.*;
import org.junit.Test;
public class AssociationTest {
@Test
public void test() {
System.out.println("===觀察者模式測試===");
Adventurer lancer = new Lancer("Jacky");
Adventurer lancer2 = new Lancer("Seven");
Adventurer bard = new Bard("Lee");
Adventurer gunman = new Gunman("longWu");
Subject association = new Association();
association.add(lancer);
association.add(lancer2);
association.add(bard);
association.add(gunman);
System.out.println("===協會派送簡單任務===");
association.sendQuestions("run");
System.out.println("===協會派送複雜任務===");
association.sendQuestions("run run run,run for your life");
System.out.println("===協會派送複雜任務===");
association.remove(lancer2);
association.sendQuestions("run run run,run for your life");
}
} /** ===觀察者模式測試=== ===協會派送簡單任務=== Jacky :單來就改,任務來就接,沒在怕的 Seven :單來就改,任務來就接,沒在怕的 Lee:當街頭藝人太難賺了,偶爾也要解任務賺點錢的 longWu:任務太簡單了,我不想理他 ===協會派送複雜任務=== Jacky :單來就改,任務來就接,沒在怕的 Seven :單來就改,任務來就接,沒在怕的 Lee:任務太難了,我只會唱歌跳舞,不接不接 longWu:只要我的手上有槍,誰都殺不死我,出發執行任務賺獎金啦!!! ===協會派送複雜任務=== Jacky :單來就改,任務來就接,沒在怕的 Lee:任務太難了,我只會唱歌跳舞,不接不接 longWu:只要我的手上有槍,誰都殺不死我,出發執行任務賺獎金啦!!! **/