For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function. Is there a way of doing this without using a switch?
A delegate is a type-safe function pointer that can reference a method that has the same signature as that of the delegate. You can take advantage of delegates in C# to implement events and call-back methods. A multicast delegate is one that can point to one or more methods that have identical signatures.
From Java 8 onwards, the lambda expression is introduced which acts as function pointers. Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies the development a lot.
Start by defining an interface that defines the method signatures of the method(s) you are pointing to. Next, create methods with the target method signature. The next step is to create variables of the wrapping interface and assign methods to them. The variables will act as a function pointer to be stored or executed.
A POINTER IS JUST THE ADDRESS OF SOME location in memory. In Java, pointers play an important role behind the scenes in the form of references to objects. A Java variable of object type stores a reference to an object, which is just a pointer giving the address of that object in memory.
What about this one?
HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
map.put(Register.ID, new Runnable() {
public void run() { functionA(); }
});
map.put(NotifyMessage.ID, new Runnable() {
public void run() { functionB(); }
});
// ...
map.get(id).run();
(If you need to pass some arguments, define your own interface with a function having a suitable parameter, and use that instead of Runnable).
Another similar approach could be using Java 8's Suppliers:
Map<Integer, Supplier<T>> suppliers = new HashMap();
suppliers.put(1, () -> methodOne());
suppliers.put(2, () -> methodTwo());
// ...
public T methodOne() { ... }
public T methodTwo() { ... }
// ...
T obj = suppliers.get(id).run();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With