實用:JAVA事件模式下PHP如何實現
發表于:2007-09-07來源:作者:點擊數:
標簽:
本文介紹了JAVA事件模式的 PHP 實現。在我以前的文章里,我概括了系統事件定義和使用call_user_func()函數建立 php 事件模塊的例子。本文通過引入高級的基于sender/eventObject/listener的php事件模塊對這個科目進行了擴展。 下面是一個JAVA 事件系統的例子
本文介紹了JAVA事件模式的
PHP實現。在我以前的文章里,我概括了系統事件定義和使用call_user_func()函數建立
php 事件模塊的例子。本文通過引入高級的基于sender/eventObject/listener的php事件模塊對這個科目進行了擴展。
下面是一個JAVA 事件系統的例子。這個例子基于Apache小組
開發的,來源于Apache.org并進行了重新縮短和重頂格式后的ProtocolCommandSupport.
java, ProtocolCommandListener.java and ProtocolCommandEvent.java文件。ProtocolCommandSupport.java文件包含了事件創建類,類的實例由系統創建,當系統被實例調用時,就就會創建該事件。事實上這個類看上去就像包含了一個監聽器---類監聽到事件創建并且在事件創建被通知時進行反應。注意“addProtocolCommandListener” and “removeProtocolCommandListener”方法,他們用于附加和分離監聽。另外2個方法fireCommandSent” and “fireReplyReceived”,召喚了對象“__listeners”容器儲存的方法。該容器實際上,只積累了ProtocolCommandListener 對象,因為只有該對象在調用addProtocolCommandListener” and “removeProtocolCommandListener”方法時能夠被通過。
ProtocolCommandSupport.java
public class ProtocolCommandSupport implements Serializable {
private Object __source;
private ListenerList __listeners = new ListenerList();
public ProtocolCommandSupport(Object source) {
__source = source;
}
/***
* Fires a ProtocolCommandEvent signalling the sending of a command to all
* registered listeners.
***/
public void fireCommandSent(String command, String message) {
Enumeration en = __listeners.getListeners();
ProtocolCommandEvent event =
new ProtocolCommandEvent(__source, command, message);
ProtocolCommandListener listener;
while (en.hasMoreElements()) {
listener = (ProtocolCommandListener)en.nextElement();
listener.protocolCommandSent(event);
}
}
/***
* Fires a ProtocolCommandEvent signalling the reception of a command reply
* to all registered listeners.
***/
public void fireReplyReceived(int replyCode, String message) {
Enumeration en = __listeners.getListeners();
ProtocolCommandEvent event =
new ProtocolCommandEvent(__source, replyCode, message);
ProtocolCommandListener listener;
while (en.hasMoreElements()) {
listener = (ProtocolCommandListener)en.nextElement();
listener.protocolReplyReceived(event);
}
}
public void addProtocolCommandListener(ProtocolCommandListener listener) {
__listeners.addListener(listener);
}
public void removeProtocolCommandListener(ProtocolCommandListener listener) {
__listeners.removeListener(listener);
}
}
ProtocolCommandListener.java 包含了監聽器接口。其后的含義是任何將要由ProtocolCommandSupport類認證的事件將要提供這個能夠實現一個足夠被事件認證接口。這就可能造成了一個新的種類,2個或更多不同的類被事件認證,因為一個類能夠實現多重接口。
ProtocolCommandListener.java
public interface ProtocolCommandListener extends EventListener {
|