My friend was given this as one of the tasks to do over the summer holidays. Him and I are very confused as to how to go on about completing this task.
The bit where it says "Your class should also take another implementation of EventConsumer in its constructor to
pass the reordered events to." is very confusing we really don't know what it's asking.
We are not looking for you to do this for us, all we're asking for is some guidance, we're quite new to programming so please go easy on us.
Here is the question:
http://postimg.org/image/snytvxvkr/
Here are the classes they have provided:
Event.java
package tests.task2;
import java.util.*;
public interface Event {
public String getEventId();
public String getEventType();
public Calendar getEventTimestamp();
}
EventConsumer.java
package tests.task2;
public interface EventConsumer {
public void consumeEvent(Event theEvent);
}
Use announcer framework to send n consume events. With the announcer framework you can even provide multiple implementations of your "EventConsumer" interface.
Check here
"Your class should also take another implementation of EventConsumer in its constructor to pass the reordered events to." =
public class MyEventConsumer implements EventConsumer {
private EventConsumer target;
public MyEventConsumer (EventConsumer target) {
// Do something with the target.
// probably you want to store it in an instance variable...
this.target = target;
}
public void consumeEvent (Event event) {
// ...so you can use it here
}
}
Related
I'm setting up an event system, and I want all my events to extend the Event class I've created. However, I also want to at any point be able to add in an additional setCanceled and isCanceled methods.
Here's an example:
public class Event {}
public interface EventCancelable {
public default void setCanceled(boolean canceled) {...}
public default boolean isCanceled() {...}
}
public class PlayerEvent extends Event {
public Player player;
public PlayerEvent(Player player) {
this.player = player;
}
}
public class PlayerMovementEvent extends PlayerEvent implements EventCancelable {...}
As you can see, I used an interface to add in the methods later.
The problem is how I have to store if an event is canceled:
public interface EventCancelable {
Map<Object, Boolean> canceled = new HashMap<>();
public void setCanceled(boolean canceled) {
canceled.put(this, canceled);
}
public boolean isCanceled() {
return canceled.get(this);
}
}
Notice since Java only allows static fields, I have to create a map to store which events are canceled. This works fine, but after a while, this will take up more and more memory considering events are being called very frequently. Is there a way to add in cancelable features without using an interface, and without manually putting the code into every event I want to be able to cancel? I can't use an EventCancelable class, since then the PlayerMovementEvent wouldn't be able to extend PlayerEvent and EventCancelable at the same time, since I don't want all PlayerEvents to be cancelable.
Or is Java smart enough to empty the map of extra events no longer used since the map is only used in the interface with this added as the argument?
You could try to use a WeakHashMap, look for an extended example here.
But, you should know there are caveats:
you have zero control or knowledge when dead entries will be removed from the Map
this puts additional pressure on the GC, as it needs to do additional work for these types of references (WeakReference under the hood of WeakHashMap)
Default methods are not meant to be used like that. They should provide implementations of methods which can have sensible defaults implemented using the other public methods of the interface.
Try composing classes:
interface Cancellable {
void cancel();
boolean isCancelled();
}
class CancellableImpl implements Cancellable {
private boolean cancelled;
...
}
class PlayerMovementEvent extends PlayerEvent implements Cancellable {
private CancellableImpl cancellable = new Cancellable();
public cancel() { cancellable.cancel(); }
public isCancelled() { return cancellable.isCancelled(); }
...
}
Only a few extra lines, but it makes things much easier to understand.
I was wondering if it's frowned upon that when designing an framework to be used by others, a class has some function as default behavior and expects its customers to override it if necessary. An example would be something like the following:
public class RecordProcessor<T extends Record> {
// ...
public void process() {
// process record logic
}
}
Consumers of this library creates their concrete classes to process their own records of type T.
Now I want to add a function called preProcess() to offer the ability for the consumers to preprocess their records. It would then look something like this:
public class RecordProcessor<T extends Record> {
// ...
public void process() {
preprocess();
// process record logic
}
public void preProcess() {
// By default no preprocessing
}
}
I know I can make preProcess an abstract function, but I dont want to due to a couple reasons:
Not all customers need to preprocess their records
We have a pipeline structure that autodeploys pushed code, so making RecordProcessor an abstract class would immediately break our customers' applications.
Is making preProcess do nothing in the parent class and let child classes override it considered bad practice? If not, what should the best way be to let customers know that they now have the power to preprocess the records? Through java docs?
One approach is to mark the public method as final (but this might also break existing apps) and allow protected hook methods to be overridden. For example:
public class RecordProcessor<T extends Record> {
// ...
public final void process() {
doPreProcess();
doProcess();
doPostProcess();
}
protected void doPreProcess() {
// By default no preprocessing
return;
}
protected void doProcess() {
// some default implementation
}
protected void doPostProcess() {
// By default no postprocessing
return;
}
}
Having some documentation should make it natural for other developers to recognize the optional extension methods.
I don't see anything wrong with having a hook method which does nothing. However, it should contain a return statement so static analysis tools won't complain.
UPDATE: in order to avoid breaking existing apps, if possible mark the existing method as deprecated and introduce a new method. For example:
public class RecordProcessor<T extends Record> {
// ...
public final void execute() {
doPreProcess();
doProcess();
doPostProcess();
}
#Deprecated - use execute() method instead.
public void process() {
doProcess();
}
protected void doPreProcess() {
// By default no preprocessing
return;
}
protected void doProcess() {
// some default implementation
}
protected void doPostProcess() {
// By default no postprocessing
return;
}
}
Prefer composition over inheritance. If you want your clients to add custom pre processing then do it by delegating to a separate objects.
public interface RecordPreProcessor<T extends Record>{
public void process(T record);
}
public class RecordProcessor<T extends Record> {
private RecordPreProcessor<T> recordPreProcessor = null;
public void setRecordPreProcessor(RecordPreProcessor<T> recordPreProcessor) {
this.recordPreProcessor = recordPreProcessor;
}
public void process() {
if (recordPreProcessor != null) recordPreProcessor.process(record);
// process record logic
}
}
No, overriding is not discouraged in Java.
The language allows overriding.
The language makes all methods overridable by default.
The Java class library includes examples of the same pattern.
Your approach is one reasonable way to allow subclasses to extend the behavior of their parent class. There are alternatives, such as passing a behavior as an object. However, there is no one true way.
One way you could improve your code is to mark preProcess() as protected. It's an implementation detail of the class. You don't want just anyone holding a RecordProcessor to decide they can call preProcess() by itself, right?
public class RecordProcessor<T extends Record> {
...
protected void preProcess() {
^^^^^^^^^
// By default no preprocessing
}
}
Another way to improve this is to consider whether you intend anyone to create an instance of the superclass RecordProcessor. If you don't, make the class abstract, to prevent that. The class name can express that, if you like, or your coding guidelines call for it.
public abstract class AbstractRecordProcessor<T extends Record> {
^^^^^^^^ ^^^^^^^^
...
protected void preProcess() {
// By default no preprocessing
}
}
One common way to document such methods is with the phrase "The default implementation does nothing. Subclasses may override this method ...". For example, below is the documentation for java.util.concurrent.FutureTask.done(). You can find more examples by searching for the first sentence of that phrase online.
public class FutureTask<V> implements RunnableFuture<V> {
...
/**
* Protected method invoked when this task transitions to state
* {#code isDone} (whether normally or via cancellation). The
* default implementation does nothing. Subclasses may override
* this method to invoke completion callbacks or perform
* bookkeeping. Note that you can query status inside the
* implementation of this method to determine whether this task
* has been cancelled.
*/
protected void done() { }
}
What I ended up doing- which I also thought was pretty good, inspired by #tsolakp, was simply creating a child class to RecordProcessor, called something like PreprocessRecordProcessor. This has no way of interfering existing code because nothing existing was touched. The class would something like this:
public class PreprocessRecordProcessor<T extends Record> extends RecordProcessor<T> {
// ...
public void process() {
preProcess();
super.process();
}
protected abstract void preProcess();
}
And if customers of this library would like to add their own logic they can simply extend this class and they'd be forced to provide pre-processing logic (as supposed to having the option to provide, which may result in unexpected results if they forgot to.)
As per definition, abstraction is hiding the implementation detail and revealing only the functionality. But exactly, what, where and which part we are hiding?
AFAIK the following program is an example of Abstraction:
public interface ToBeImplemented {
public string doThis();
}
public class Myclass implements ToBeImplemented {
#override
public string doThis() {
//Implementation
return null;
}
}
If I am wrong and this is not abstraction then what is the correct example of Abstraction?
In the above example you can write something like this:
public interface ToBeImplemented {
public string doThis();
}
public class ImplementationA implements ToBeImplemented {
#override
public string doThis() {
//ImplementationA of doThis
return null;
}
}
public class ImplementationB implements ToBeImplemented {
#override
public string doThis() {
//ImplementationB of doThis
return null;
}
}
Then you can have another class, and a main method for example:
class SomeClass{
public static void main(String[] args) {
ToBeImplemented someImplementation;
//now you can pick an implementation, based on user input for example
if (userInput == something)
someImplementation = new ImplementationA();
else
someImplementation = new ImplementationB();
//do some staff
//Regardless of the user input, main method only knows about the
//abstract "ToBeImplemented", and so calls the .doThis() method of it
//and the right method gets called based on the user input.
someImplementaion.doThis();
//at That
}
}
The abstraction is that you can declare a ToBeImplemented reference, and then assign to it either ImplementationA, or ImplementationB (and possibly any other implementation). But you write your code against the abstract ToBeImplemented, and let some conditions decide what the right implementation of ToBeImplemented (and, as a result doThis()) should be called.
Your definition of abstraction is correct. And the code you provided is definitely a form of abstraction.
Why?
Because the user of your code will only be provided with the interface. The user will only know that your code doThis() does a certain task but he/she won't know how the code does that certain task.
For example:
public interface myInterface{
public int sumTo(n);
}
public class myClass implements myInterface{
public int sumTo(int n){
int sum=0;
for(int i=0; i<=n; i++){
sum+=i;
}
return sum;
}
}
In this example, the user will only get the interface so he/she only knows that your code can sum up to n. But the user won't know that you used a for loop to sum up to n.
Wikipedia is a good place to start your learning: Abstraction (computer science)
The essence of abstractions is preserving information that is relevant in a given context, and forgetting information that is irrelevant in that context.
John V. Guttag
Separating interface from implementation is one way to provide abstraction.
The Collections framework in Java is an excellent example. Calling apps work with variables (references) declared as the interface such as List or Map while the actual object in play is really a concrete class such as ArrayList or HashMap.
If the interface provides all needed functionality, then there is no need for the calling app to know about the underlying implementation.
The example code shown in the Question is an example of separating interface from implementation, and therefore of abstraction. That example would be greatly improved if it used a specific meaningful context such as BankAccount as the interface and SavingsAccount and CheckingAccount as the implementations.
Let's say I have some variable defined using the statementint someVariable;. While the code runs, the variable's value changes.
How can I track the changes in this variable? How could I implement some Listener that behaves like onSomeVariableChangedListener?
I also need to know when some other method in one page has been executed so I can set a Listener in another class.
Java gives you a simple Observer pattern implementation for this kind of thing, but you'll need to set your observed variable within a method that manages listener notifications. If you can't extend Observable, you can either use composition (i.e., have an Observable instance in your class to manage notifications), or you can take a look at java.util.Observable to get an idea of how to roll your own version.
Flux.java
import java.util.Observable;
public class Flux extends Observable {
private int someVariable = 0;
public void setSomeVariable(int someVariable) {
synchronized (this) {
this.someVariable = someVariable;
}
setChanged();
notifyObservers();
}
public synchronized int getSomeVariable() {
return someVariable;
}
}
Heraclitus.java
import java.util.Observable;
import java.util.Observer;
public class Heraclitus implements Observer {
public void observe(Observable o) {
o.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
int someVariable = ((Flux) o).getSomeVariable();
System.out.println("All is flux! Some variable is now " + someVariable);
}
}
This is one of the many reasons to hide variables behind setter/getter pairs. Then, in the setter you can notify your listener that this variable has been modified in the appropriate way. As the others have commented, there is no built in way to do exactly what you want, you need to implement it yourself.
Alternatively Benjamin brings up an interesting pattern, called the Decorator pattern, which might be useful to you if the code in question cannot be modified. You can look up more info at Wikipedia
The idea is to build a compatible wrapper around an object. Lets say your object in question is of type MyClass.
class MyClass{
public void doFunc(){...}
}
class MyLoggedClass extends MyClass{
MyClass myObject;
public void doFunc(){
//Log doFunc Call
myObject.doFunc();
}
}
instead of
MyClass object = new MyClass();
You would use
MyClass object = new MyLoggedClass(new MyClass());
Now your rest of the code would use object as per normal, except that each function call will be logged, or notified, etc.
As you will see in Wikipedia, this is typically done via an interface that the class in question inherits from, but this may not be possible in your case.
You could use View Model. First create a class that extends view model. I called mine NameViewModel.
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
public class NameViewModel extends ViewModel {
private MutableLiveData<String> currentName;
public MutableLiveData<String> getCurrentName(){
if(currentName == null){
currentName = new MutableLiveData<>();
}
return currentrName;
}
}
then in activity that the variable value change first define an instance of your NameViewModel class :
private NameViewModel mNameViewModel;
then in onCreate use this code snippet
mNameViewModel = ViewModelProvider.of(this).get(NameViewModel.class)
mNameViewModel.getCurrentName().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String name) {
//do what you want when the varriable change.
}
});
if you want to change the value of name you could use this code snippet:
mNameViewModel.getCurrentName().postValue(String newName);
I use postValue() since I want to update variable from worker thread if you are on UI thread you should use setValue().
Now every time the variable are changed it update the UI.
I believe you will have to implement Observer Pattern.
There is no built-in way in Java to get a notification if the value of any arbitrary variable changes or if some method has been called.
What should be the preferable Java interface or similar pattern that could be used as a generic callback mechanism?
For example it could be something like
public interface GenericCallback
{
public String getID();
public void callback(Object notification);
// or public void callback(String id, Object notification);
}
The ID would be needed for cases of overriden hashCode() methods so that the callee identifies the caller.
A pattern like the above is useful for objects that needs to report back to the class they were spawned from a condition (e.g., end of processing).
In this scenario, the "parent" class would use the getID() method of each of these GenericCallback objects to keep a track of them in a Map<String, GenericCallable> and add or remove them according to the notification received.
Also, how should such an interface be actually named?
Many people seem to prefer the Java Observer pattern, but the Observable class defined there is not convenient, since it not an interface to circumvent single inheritance and it carries more functionality than actually needed in the above, simple scenario.
I would genericize the callback, based upon the type of Object passed. This is particularly useful for EventListeners listening for different classes of events. e.g.
public interface Callback<T> {
public void callback(T t);
}
You may be able to use the type T as the key in a Map. Of course, if you want to differentiate between two callbacks that take the same argument, like a String, then you'd need something like your getID().
Here my old blog about using this for Event Listeners The interface Events.Listener corresponds to Callback<T> above. And Broadcasters uses a Map to keep track of multiple listeners based upon the class they accept as the argument.
I'd recommend using Observer pattern since the Observer pattern is the gold standard in decoupling - the separation of objects that depend on each other.
But I'd recommend avoiding using the Java.util.Observable class if you are looking for a generic callback mechanism. Because Observable has a couple of weaknesses: it's not an interface, and forces you to use Object to represent events.
You can define your own event listener like this:
public class MyEvent extends EventObject {
public MyEvent(Object source) {
super(source);
}
}
public interface MyEventListener {
void handleEvent(EventObject event);
}
public class MyEventSource {
private final List<MyEventListener> listeners;
public MyEventSource() {
listeners = new CopyOnWriteArrayList<MyEventListener>();
}
public void addMyEventListener(MyEventListener listener) {
listeners.add(listener);
}
public void removeMyEventListener(MyEventListener listener) {
listeners.remove(listener);
}
void fireEvent() {
MyEvent event = new MyEvent(this);
for (MyEventListener listener : listeners) {
listener.handleEvent(event);
}
}
}
looks like you want to implement the Observer pattern. In this url is a complete implementation for the observer pattern in Java. In your case the observer will be the callback.
Also If you need to implement something more complex, you will end up doing an event/notifier pattern. Take a look at this other pattern here.
Thanks,
#leo.
Callbacks in Java8 can now be done with the java.util.function package.
See Java 8 lambda Void argument for more information.