(一)設計モード復習の観察者モード


観察者パターンは普段から多く使われていますが、理論の基礎が悪い仲間にとっては、自分が観察者パターンを使っていることを知らないことが多いです.「オブザーバーモード」とは何か、
例えば私たちJavaのボタンのクリックイベントは実は「オブザーバーモード」です
<span style="white-space:pre">	</span>JButton button = new JButton("  ");
<span style="white-space:pre">	</span>button.addActionListener(new ActionListener() {
			
	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println("     ");
	}
<span style="white-space:pre">	</span>});
     “     ”,   JButton       ,               “  ”; ActionListener            button
         “   ”(      )。
          “     ” ?           ,           ,                 ;            
        ,        。
    (TestA)    :
public class TestA {

private String str = "    ";
private TestB b;
private TestC c;

<span style="white-space:pre">	</span>public TestA(){
		System.out.println("     ");
<span style="white-space:pre">	</span>}

	public void regiest(TestB b,TestC c){
		this.b = b;
		this.c = c;
	}

<span style="white-space:pre">	</span>public void giveRice(){
		b.buyRice(str);
		c.buyRice(str);
<span style="white-space:pre">	</span>}

}
   (TestB);    :
public class TestB {
	
	private String strTag = "TestB  ";
	
	public TestB(){
		System.out.println("     ");
	}
	
	public void buyRice(String str){
		System.out.println(strTag+str);
	}
	
}
TestCとTestBは同じコードです.
 
 
  TestA regiest()/giveRice();        /  ,                      TestA register()/giveRice()  ,
    ,        ;     ,       ,     ?             ,     “  ”,     “   ”;
      “  ”(TestA_1):public class TestA_1 {
	
	private String str = "    ";
	
	private ArrayList<BuyRiceListener> buyrices = new ArrayList<BuyRiceListener>();
	
	public TestA_1(){
		System.out.println("     ");
	}
	
	public void regiest(BuyRiceListener listener){

		buyrices.add(listener);
	}
	
	public void remove(BuyRiceListener listener){
		//             
		int i = buyrices.indexOf(listener);
		if(i > 0){
			buyrices.remove(i);
		}
	}
	
	public void giveRice(){

		for(BuyRiceListener listener : buyrices){
			listener.buyRice(str);
		}
	}
	
	public interface BuyRiceListener {
		public void buyRice(String str);
	}
	
}
    “   ”(TestB), :TestB TestC     :<pre name="code" class="html">public class TestB_1 implements BuyRiceListener {
	
	private String strTag = "TestB  ";
	
	public TestB_1(TestA_1 a){
		System.out.println("     ");
		a.regiest(this);
	}
	
	public void buyRice(String str){
		System.out.println(strTag+str);
	}
	
}
 testa testa_1         ,  testa_1              testa_1   ,    testa_1    new testb_1         
        
public static void main(String[] args) {
	TestA a = new TestA();
		
	TestB b = new TestB(a);
	TestC c = new TestC(a);
		
	a.giveRice();
}
             ,               ,              ;
     ,    ,           ,             ,    ......           ......
“     ”               ,          ,             。