假设有这样一个场景,app第一个页面是一个正方形,第二个页面有一个按钮,点击第一个的某按钮后,跳转到第二个页面,第二个页面修改正方形的边长,然后返回第一个页面,此时当前页面的矩形变化。
import java.util.Objects;
/**
* Created by itfanr on 14/11/11.
*/
public interface ClickDelegate {
public void lengthDidChange(SecondPage sp , int length) ;
}
/**
* Created by itfanr on 14/11/11.
*/
public class FirstPage implements ClickDelegate {
private int area ;
@Override
public void lengthDidChange(SecondPage sp, int length) {
this.area = length *2 ;
System.out.println("back to first page");
System.out.println("area is also changed : " + this.area+ "\n");
}
public SecondPage jumpToSecond(){
System.out.println("jump to second page");
SecondPage sp = new SecondPage() ;
sp.cd = this ;
return sp ;
}
}
/**
* Created by itfanr on 14/11/11.
*/
public class SecondPage {
private int length = 10;
public ClickDelegate cd = null ;
public void click() {
System.out.println("clicked in second page !");
this.length++;
if (this.cd != null) {
System.out.println("length is " + this.length);
this.cd.lengthDidChange(this, this.length) ;
}
}
}
/**
* Created by itfanr on 14/11/11.
*/
public class Client {
public static void main(String args[]){
FirstPage fp = new FirstPage() ;
SecondPage sp = fp.jumpToSecond();
sp.click();
sp.click();
}
}
输出结果如下:
jump to second page
clicked in second page !
length is 11
back to first page
area is also changed : 22
clicked in second page !
length is 12
back to first page
area is also changed : 24
感觉和普通的观察者模式有点不同。如果是普通的观察者模式,应该是第二个页面观察第一个页面的变化。