I'm working on a game engine, and the last question I had regarding this was what good way I can use to make "observers" or listeners. A user suggested that I should use Java's EventObject class to inherit from and make a Listener interface. However, this didn't provide me with good flexibility.
Here is the Handler annotation to state that a method is an event handler in a listener:
#Retention(RetentionPolicy.CLASS)
#Target(ElementType.METHOD)
public #interface Handler {}
Here is the base class for Event, which is basically the same as EventObject (but I'll add abstract methods sooner or later):
public abstract class Event {
private Object source;
public Event(Object source) {
this.source = source;
}
public Object getSource() {
return source;
}
}
Here is the Listener class, which is empty:
public interface Listener {}
Here is the ListenerHandler class, used to handle all listeners. You register and unregister them here. I'll edit the register/unregister methods later for a better use:
public class ListenerHandler {
private ArrayList<Listener> listeners;
public ListenerHandler() {
this.listeners = new ArrayList<Listener>();
}
public void registerListener(Listener l) {
listeners.add(l);
}
public void unregisterListener(Listener l) {
listeners.remove(l);
}
public void onEvent(Event event) {
for(Listener l : listeners) {
Class<?> c = l.getClass();
Method[] methods = c.getDeclaredMethods();
for(Method m : methods) {
if(m.isAccessible()) {
if(m.isAnnotationPresent(Handler.class)) {
Class<?>[] params = m.getParameterTypes();
if(params.length > 1) {
continue;
}
Class<?> par = params[0];
if(par.getSuperclass().equals(Event.class)) {
try {
m.invoke(this, event);
}catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
From what I heard, it's a use of a lot of memory in order to get all methods of a class. I'm not going to assume this is the case, but I'm sure there is a better way as this will be a game engine with many components and such.
I'd like to know the best way to implement this, or if I'm doing it right. I'd also like to know if anyone can help me improve this in any way without hogging memory usage by the game (as of now it's not a big deal -- the "game engine" is not even close to rendering anything yet)
I tried to keep it a very simple example and will comment with different ideas to it:
First meet the Achievement class:
import java.util.Observable;
public class Achievement extends Observable {
public static class AchievementDetails {}
public Achievement() {
addObserver(EventsListener.getInstance());
}
public void achievementReached() {
AchievementDetails achievemetDetails = null;
setChanged();
notifyObservers(achievemetDetails);
}
}
And then the events listener class:
import com.test.Achievement.AchievementDetails;
public class EventsListener implements Observer {
private static EventsListener instance = new EventsListener();
public static EventsListener getInstance() {
return instance;
}
#Override
public void update(Observable o, Object arg) {
if(o instanceof Achievement) {
AchievementDetails achievemetDetails = (AchievementDetails) arg;
//do some logic here
}
}
}
The only one thing that is missing is to create an instance of your achievement (which register the EventsListener to itself) and handle the life cycle of it.
Related
I'm trying to write a generic code. Here is my scenario.
class AEvent {
public void onAEventCreate( A event){
//do something
}
}
class BEvent {
public void onBEventCreate (B event) {
//do something
}
}
I want to have some generic class which could do the operation of method onAEventCreate and onBEventCreate on one single method. Now the catch is I do not want to change the classes AEvent and BEvent . Is there a way I can listen to the two methods? or is there some kind of design pattern maybe like observer which can help me achieve this.
There are a lot of ways to do this, if you want to use the Observe Pattern an example would be :
You create an ObserverEvent class
class EventObserver {
private AEvent aEvent;
private BEvent bEvent;
public EventObserver(AEvent aEvent, BEvent bEvent) {
this.aEvent = aEvent;
this.bEvent = bEvent;
aEvent.setObserver(this);
bEvent.setObserver(this);
}
public void onEventCreated() {
if (aEvent.isAEventCreated && bEvent.isBEventCreated) {
onBothEventsCreated();
}
}
public void onBothEventsCreated() {
//this method will be called when both events are created
}
}
Then you need to adapt your classes to this :
class BEvent {
private boolean isBEventCreated = false;
private EventObserver observer;
public void setObserver(EventObserver observer) {
this.observer = observer;
}
public void onBEventCreated() {
this.isBEventCreated = true;
observer.onEventCreated();
}
}
And the same with AEvent.
in this below class i try to handle all events on application. i dont like to write some class to handle theme, in EventBus documentation, that use class constructor, my class must be singleton to be has public, then i wrote simple class as :
public class SignalEvents {
private boolean internetConnectionState;
private boolean activityMarketDetailState;
public boolean isInternetConnectionState() {
return internetConnectionState;
}
public void setInternetConnectionState(boolean internetConnectionState) {
this.internetConnectionState = internetConnectionState;
}
public boolean isActivityMarketDetailState() {
return activityMarketDetailState;
}
public void setActivityMarketDetailState(boolean activityMarketDetailState) {
this.activityMarketDetailState = activityMarketDetailState;
}
}
now, for eventBus and send event i try to use:
SignalEvents signal = new SignalEvents();
EventBus.getDefault().post(signal.setActivityMarketDetailState(true));
but then i get error :
Error:(98, 67) error: 'void' type not allowed here
You need to post objects. For example:
EventBus.getDefault().post(new ActivityMarketDetailStateChanged(true));
And have such a class:
public class ActivityMarketDetailStateChanged {
public final boolean newState;
public ActivityMarketDetailStateChanged(boolean newState) {
this.newState = newState;
}
}
And then register to subscribe to those events, depending on if you are using EventBus 2.x or 3.x, assuming version 3:
EventBus.getDefault().register(signal);
Need a subscribe method to receive it in your SignalEvents class:
#Subscribe
public void onEvent(ActivityMarketDetailStateChanged event) {
setActivityMarketDetailState(event.newState);
}
I'm trying to make an annotation-based event system where like you would register a class implementing an interface and then you can use the events that have an #interface above the methods that are called. Like so:
Wherever.java
EventManager.callEvent(new HelloEvent);
EventManager.register(new ClassThatImplementsListeenr);
#EventHandler
public void onHello(HelloEvent event) {
event.sayHello();
}
Ok I understand a lot of this like registering (adds them to arraylist) and making a listener interface plus Event interface. New Events will implement Event, and an #Interface called EventHandler that will only work with methods. THE MAIN part is what I don't get. How to invoke and check for the annotation.
EDIT I JUST MADE THIS, WOULD IT WORK?
Public class EventManager {
private static List<Listener> registered = new ArrayList<Listener>();
public static void register(Listener listener) {
if (!registered.contains(listener)) {
registered.add(listener);
}
}
public static void unregister(Listener listener) {
if (registered.contains(listener)) {
registered.remove(listener);
}
}
public static List<Listener> getRegistered() {
return registered;
}
public static void callEvent(final Event event) {
new Thread() {
public void run() {
call(event);
}
}.start();
}
private static void call(final Event event) {
for (Listener listener : registered) {
Method[] methods = listener.getClass().getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(EventHandler.class)) {
try {
method.invoke(listener.getClass().newInstance(), event);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
}
}
You can check for annotations that have been added to a method by
Retrieving all the methods that are available on a class:
public void registerListeners(T handler){
Method[] allMethods = handler.getClass().getMethods();
}
Check all the methods that have your desired annotation (although I would imagine only one method in any given class should be designated with an event listener-type annotation)
List<Method> listenerMethods = new ArrayList<Method>();
for (Method aMethod: allMethods){
if(aMethod.isAnnotationPresent(EventHandler.class)){
listenerMethods.add(aMethod);
}
}
Given the specific methods that have the annotation, you could call Method#invoke on the shortlist of methods to execute the listener.
I cannot seem to find an answer anywhere to my question. Is there any event listener which can detect the changing of a boolean or other variable and then act on it. Or is it possible to create a custom event listener to detect this?
Please I cannot seem to find a solution to this anywhere and I found this website explaining how to create custom events
Use PropertyChangeSupport. You wont have to implement as much and it is thread safe.
public class MyClassWithText {
protected PropertyChangeSupport propertyChangeSupport;
private String text;
public MyClassWithText () {
propertyChangeSupport = new PropertyChangeSupport(this);
}
public void setText(String text) {
String oldText = this.text;
this.text = text;
propertyChangeSupport.firePropertyChange("MyTextProperty",oldText, text);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
}
public class MyTextListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals("MyTextProperty")) {
System.out.println(event.getNewValue().toString());
}
}
}
public class MyTextTest {
public static void main(String[] args) {
MyClassWithText interestingText = new MyClassWithText();
MyTextListener listener = new MyTextListener();
interestingText.addPropertyChangeListener(listener);
interestingText.setText("FRIST!");
interestingText.setText("it's more like when you take a car, and you...");
}
}
Just like you need to create an event listener, you will also need to create the event firer -- since there is nothing automatic that will do this for you. I've provided sample code that shows you how to implement such a firer.
This test implementation isn't perfect. It only includes a way to add listeners. You may wish to include a way to remove listeners who are no longer interested in receiving events. Also note that this class is not thread-safe.
import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue;
/**
* This class uses the EventQueue to process its events, but you should only
* really do this if the changes you make have an impact on part of a GUI
* eg. adding a button to a JFrame.
*
* Otherwise, you should create your own event dispatch thread that can handle
* change events
*/
public class BooleanChangeTest implements BooleanChangeDispatcher {
public static void main(String[] args) {
BooleanChangeListener listener = new BooleanChangeListener() {
#Override
public void stateChanged(BooleanChangeEvent event) {
System.out.println("Detected change to: "
+ event.getDispatcher().getFlag()
+ " -- event: " + event);
}
};
BooleanChangeTest test = new BooleanChangeTest(false);
test.addBooleanChangeListener(listener);
test.setFlag(false); // no change, no event dispatch
test.setFlag(true); // changed to true -- event dispatched
}
private boolean flag;
private List<BooleanChangeListener> listeners;
public BooleanChangeTest(boolean initialFlagState) {
flag = initialFlagState;
listeners = new ArrayList<BooleanChangeListener>();
}
#Override
public void addBooleanChangeListener(BooleanChangeListener listener) {
listeners.add(listener);
}
#Override
public void setFlag(boolean flag) {
if (this.flag != flag) {
this.flag = flag;
dispatchEvent();
}
}
#Override
public boolean getFlag() {
return flag;
}
private void dispatchEvent() {
final BooleanChangeEvent event = new BooleanChangeEvent(this);
for (BooleanChangeListener l : listeners) {
dispatchRunnableOnEventQueue(l, event);
}
}
private void dispatchRunnableOnEventQueue(
final BooleanChangeListener listener,
final BooleanChangeEvent event) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
listener.stateChanged(event);
}
});
}
}
interface BooleanChangeDispatcher {
public void addBooleanChangeListener(BooleanChangeListener listener);
public boolean getFlag();
public void setFlag(boolean flag);
}
/**
* Listener interface for classes interested in knowing about a boolean
* flag change.
*/
interface BooleanChangeListener extends EventListener {
public void stateChanged(BooleanChangeEvent event);
}
/**
* This class lets the listener know when the change occured and what
* object was changed.
*/
class BooleanChangeEvent extends EventObject {
private final BooleanChangeDispatcher dispatcher;
public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
super(dispatcher);
this.dispatcher = dispatcher;
}
// type safe way to get source (as opposed to getSource of EventObject
public BooleanChangeDispatcher getDispatcher() {
return dispatcher;
}
}
you can also try to implement an Observer.
First create the observable object:
import java.util.Observable;
public class StringObservable extends Observable {
private String name;
public StringObservable(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}
}
Then the observer:
import java.util.Observable;
import java.util.Observer;
public class NameObserver implements Observer {
private String name;
public NameObserver() {
name = null;
}
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
name = (String) arg;
System.out.println("NameObserver: Name changed to " + name);
} else {
System.out.println("NameObserver: Some other change to subject!");
}
}
}
And in your main (or wherever else):
public class TestObservers {
public static void main(String args[]) {
// Create the Subject and Observers.
StringObservable s = new StringObservable("Test");
NameObserver nameObs = new NameObserver();
// Add the Observer
s.addObserver(nameObs);
// Make changes to the Subject.
s.setName("Test1");
s.setName("Test2");
}
}
Mostly found here
Very late to answer, but this is a problem that can be solved with Observer/Observable. Example
The boolean you are setting should be allowed to do only through a setter method like:
public void setFlag(boolean flag){
//Method code goes here
}
Now in now set method, you can decide based on what value comes in, what event needs to be fired. I am explaining in simple terms without introducing complex terms so you can understand better, so code snippet would look like:
public void setFlag(boolean flag){
//if flag is TRUE do something
//If flag is FALSE then do something
//And finally do what you needed to do with flag
}
Ask questions if you need more info
you create a listener when you want to listen for I/O changes. mostly on graphics.
the answer to your question is to keep state of the running program, then check if variables change from the state inside the infinite loop of your program.
You can use AOP for that, perhaps AspectJ? Check a few examples here (if you use Eclipse, then using AspectJ is really simple with their plugin).
For you, you would have a pointcut similar to the one used in the SampleAspect, but one that will only be used when someone makes a new SET to a boolean variable (this doesn't mean that the value has changed, just that someone loaded a value to the variable).
Dependency injection is a useful technique but what approach is recommended when faced with runtime dependencies?
e.g. Say you want to glue an event to an event processor depending on the type of the event and the user who initiated the request.
public interface Event {}
public interface EventProcessor {
public void handleEvent(Event e);
}
class EventProcessorFactory {
private final User u;
private final Event e;
public EventProcessorFactory(User u, Event e) {
this.u = u;
this.e = e;
}
public EventProcessor get() {
EventProcessor ep;
if(e instanceof LocalEvent) {
ep = new LocalEventProcessor();
}
else if(e instanceof RemoteTriggeredEvent && u instanceof AdminUser) {
//has static dependencies
ep = new RemoteEventProcessor(u);
}
else {
ep = new DefaultEventProcessor();
}
}
}
Now the complexity is encapsulated in the factory, but how else could I achieve the same result, without too much boilerplate code?
As written, what you call 'boilerplate code' looks to me to be just 'code'. You have some processing logic that needs to be stated somewhere (local events go to a local event processor, etc). Trying to avoid explicitly stating that logic could be a mistake.
If it is what you do want to do, the simplest way of doing it is to change the interface to add a method:
boolean isInterestedInEvent(Event e)
then set up all the event processors and loop over them until you find the right one.
You could use something like
public interface EventProcessor {
public boolean supports(Event event, User user);
public void handleEvent(Event event);
}
class EventProcessorFactory {
public void setEventProcessors(List<EventProcessor> processors) {
this.processors = processors;
}
public EventProcessor get(Event event, User user) {
for (EventProcessor processor : processors) {
if (processor.supports(event, user)
return processor;
}
}
}
class LocalEventProcessor implements EventProcessor {
public boolean supports(Event event, User user) {
return (event instanceof LocalEvent);
}
// etc
}
class RemoteEventProcessor implements EventProcessor {
public boolean supports(Event event, User user) {
return (event instanceof RemoteTriggeredEvent) &&
(user instanceof AdminUser);
}
// etc
}
If your processors have some sort of natural ordering, you can implement Comparable to ensure they are tested in the correct order, otherwise you'll can rely on them being injected into the factory in the required order, thus making it configurable.
You could make each Event responsible for creating the EventProcessor. That way you reduce the number of instanceof checks you're required to make and also achieve better encapsulation. Despite being more "OO" the trade-off is that the logic is no longer in one place (i.e. sometimes it's better to just stick with a "procedural approach" as per your example).
public interface Event {
EventProcessor createProcessor(User u);
}
public class RemoteTriggeredEvent implements Event {
public EventProcessor createProcessor(User u) {
return (u instanceof AdminUser) ? new RemoteEventProcessor(u) :
new DefaultEventProcessor();
}
}