<1 >
<2 publisher >
public class Publisher {
private List<Subscriber> list=new ArrayList<>();
public void attach(Subscriber subscriber){
list.add(subscriber);
}
public void dettach(Subscriber subscriber){
list.remove(subscriber);
}
public void noti(){
for (Subscriber sb: list ) {
sb.updata(this);
}
}
}
❤️ >
public class MagazinePublisher extends Publisher{
}
<4>
//订阅者
public interface Subscriber {
//拿到消息,更新自己
void updata(Publisher publisher);
}
<5>
public class StudentSub implements Subscriber{
@Override
public void updata(Publisher publisher) {
Log.d("xn","我真的不想看");
}
}
<6>
public class TeacherSub implements Subscriber{
@Override
public void updata(Publisher publisher) {
Log.d("xn","我也想获得这种吹牛的能力");
}
}
<7 mainactivity主页面>
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tv);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
test();
}
});
}
private void test(){
//初始化发布者对象
MagazinePublisher publisher=new MagazinePublisher();
//初始化订阅者对象
StudentSub studentSub=new StudentSub();
TeacherSub teacherSub=new TeacherSub();
//添加订阅者
publisher.attach(studentSub);
publisher.attach(teacherSub);
//杂志社发行新刊
publisher.noti();
}
}