标签:
场景:犯罪集团专门负责贩毒和洗黑钱2种犯罪活动。公安部新成立2个部门,一个负责扫毒,一个负责打击洗钱犯罪。公安部决定派出卧底,打入犯罪集团的内部,获取犯罪集团的证据和在犯罪活动的发生时通知对应的部门,进行逮捕行动。
犯罪集团:
public class CrimeGroup extends Observable {
private boolean isFanDu;
private boolean isXiQian;
public void setFandu(boolean isFandu){
this.isFanDu = isFandu;
if (isFandu){
setChanged();
}
}
public void setXiQian(boolean isXiQian){
this.isXiQian = isXiQian;
if (isXiQian){
setChanged();
}
}
public boolean isFanDu() {
return isFanDu;
}
public boolean isXiQian() {
return isXiQian;
}
}
逮捕行动:
public interface ICatch {
void grab();
}
警察(公安):
public abstract class Police implements Observer ,ICatch{
}
专门负责扫毒的警察:
public class SaoDuPolice extends Police {
public SaoDuPolice(){
}
@Override
public void update(Observable observable, Object data) {
if (observable!=null&&data!=null){
CrimeGroup crimeGroup = (CrimeGroup) observable;
boolean fanDu = crimeGroup.isFanDu();
if (data instanceof SaoDuPolice){//验明身份
if (fanDu){//证据确凿
grab();//逮捕
}
}
}
}
@Override
public void grab() {
Log.e("zhang", "你在贩毒证据确凿,我将对你实施逮捕" );
}
}
专门负责洗黑钱的警察:
public class XiQianPolice extends Police {
private boolean isXiQian;
public XiQianPolice(){
}
@Override
public void update(Observable observable, Object data) {
if (observable!=null && data!=null){
CrimeGroup crimeGroup = (CrimeGroup) observable;
boolean xiQian = crimeGroup.isXiQian();
if (data instanceof XiQianPolice){
if (xiQian){
grab();
}
}
}
}
@Override
public void grab() {
Log.e("zhang", "你在洗钱证据确凿,我将对你实施逮捕" );
}
}
在程序入口调用init()方法
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
CrimeGroup crimeGroup = new CrimeGroup();
SaoDuPolice wodi1 = new SaoDuPolice();
crimeGroup.addObserver(wodi1);//派卧底打入犯罪集团内部(注册)
XiQianPolice wodi2 = new XiQianPolice();
crimeGroup.addObserver(wodi2);
crimeGroup.setFandu(true);//犯罪集团在贩毒
crimeGroup.notifyObservers(wodi1);//表明身份,通知扫毒的警察
crimeGroup.setXiQian(true);
crimeGroup.notifyObservers(wodi2);
}
}
Observable这个抽象类和Observer接口是java.util包下的,系统提供的。
标签:
原文地址:http://blog.csdn.net/qq_33689414/article/details/51332942