One may write a couple of classes and an interface to achieve event handling without having to implement the Observable/Observer interface. Assume, we have a computer that runs several processes. If it receives a shutdown command, we fire an event to let the running process handle its own clean up method to release resources and halt execution.
interface ShutdownListener{
public void handle();
}
public class Computer{
private def listeners = []
def addShutdownListener(ShutdownListener l){
listeners.add(l)
}
def shutdown(){
for(ShutdownListener l : listeners)
l.handle()
}
def compute(){ // whatever }
}
public class Process implements ShutdownListener{
public void handle(){
// release resources of "this" Process
// halt execution of self
println("Process ended.");
}
}
//groovy script start
def computer = new Computer()
def process = new Process()
computer.addShutdownListener(process)
computer.compute()
computer.shutdown()
interface ShutdownListener{
public void handle();
}
public class Computer{
private def listeners = []
def addShutdownListener(ShutdownListener l){
listeners.add(l)
}
def shutdown(){
for(ShutdownListener l : listeners)
l.handle()
}
def compute(){ // whatever }
}
public class Process implements ShutdownListener{
public void handle(){
// release resources of "this" Process
// halt execution of self
println("Process ended.");
}
}
//groovy script start
def computer = new Computer()
def process = new Process()
computer.addShutdownListener(process)
computer.compute()
computer.shutdown()
0 comments:
Post a Comment