简单的对象监听器 观察者设计模式
該代碼實現了一個可以注冊監聽類的類,如果注冊了監聽類,那么在類的一個方法執行前會執行監聽類的方法。并且該監聽類方法的參數就是被監聽對象。
監聽類就是事件監聽器,被監聽對象就是事件源,事件監聽器的參數就是事件對象。
//設計一個事件源,被監聽器監聽? Observer(觀察者設計模式)
public class Demo2 {
?
?????? public static void main(String[] args) {
?????????????
????????????? Person p = new Person();
????????????? p.registerListener(new PersonListener(){
?
???????????????????? public void doeat(Event e) {
??????????????????????????? Person p = e.getSource();
??????????????????????????? System.out.println(p + "吃個死");
???????????????????? }
?
???????????????????? public void dorun(Event e) {
??????????????????????????? // TODO Auto-generated method stub
???????????????????? }
????????????????????
?
????????????? });
????????????? p.eat();
?????? }
?
}
?
class Person{
??????
?????? private PersonListener listener;
??????
?????? public void eat(){
????????????? if(listener!=null){
???????????????????? listener.doeat(new Event(this));
????????????? }
?????? }
??????
?????? public void run(){
????????????? if(listener!=null){
???????????????????? listener.dorun(new Event(this));
????????????? }
?????? }
??????
?????? public void registerListener(PersonListener listener){
????????????? this.listener = listener;
?????? }
}
?
interface PersonListener{
??????
?????? public void doeat(Event e);
??????
?????? public void dorun(Event e);
??????
}
?
class Event{
??????
?????? private Person source;
?????? public Event() {
????????????? super();
????????????? // TODO Auto-generated constructor stub
?????? }
?
?????? public Event(Person source) {
????????????? super();
????????????? this.source = source;
?????? }
?
?????? public Person getSource() {
????????????? return source;
?????? }
?
?????? public void setSource(Person source) {
????????????? this.source = source;
?????? }
??????
}
轉載于:https://www.cnblogs.com/flying607/p/3469133.html
總結
以上是生活随笔為你收集整理的简单的对象监听器 观察者设计模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 转载ASP.NET MVC 中@Html
- 下一篇: 举例详细说明javascript作用域、