How to subscribe to property in created object in java - java

I have a class which implement an interface from third part library and one of methods is passing object of class called Velocity.
How I can listen to specific variable value changes in this object?
Here is the code for better understanding.
This is interface from the third part library :
public interface MotionListener {
void onObjectMoved(Velocity velocity);
void onObjectStopped();
}
and the Velocity class is packed in the library and it is very simple.
The class has 3 attributes.
I implemented this interface in my class as follows:
public class MyCar implements MotionListener {
#Override
public void onObjectMoved(Velocity velocity) {
System.out.println("Distance" + velocity.getDistance());
System.out.println("Speed" + velocity.getSpeed());
System.out.println("widnowIsOpened" + velocity.widnowIsOpened());
/*
I need here to set up a listener for the boolean value widnowIsOpened
because this boolean may be change later and this method will not be invoked again
, it is just invoked once but
value of windowIsOpened may change by the library
*/
}
#Override
public void onObjectStopped() {
}
// other methods ...
}
What I need is to listen to the boolean value changes to react to the changes in my code. I did a lot of searching on this topic, but all possible solutions that i found if I have access to Velocity class so I can set listener inside the Velocity class,
but in my case I have only the passed object.
So the only thing I can do is to check if the
widnowIsOpened is true or false, but not for change.
Any help?

You can write your custom listener class with some method in that class. Call that method of listener class inside onObjectMoved() method based on the boolean value.
If you want to send update to multiple listeners, then write a interface for listener and writes its implementations.
If you want I can share some piece of code with you.
Here you go:
public class MyCar implements MotionListener {
private VelocityListener listener;
// added constructor
public MyCar(VelocityListener listener) {
this.listener = listener;
}
#Override
public void onObjectMoved(Velocity velocity) {
System.out.println("Distance" + velocity.getDistance());
System.out.println("Speed" + velocity.getSpeed());
System.out.println("isMoving" + velocity.isMoving());
// added handling
listener.doSomething(velocity);
// I need here to set up a listener for the boolean value isMoving
}
#Override
public void onObjectStopped() {
}
public static void main(String[] args) {
MyCar car = new MyCar(new VelocityListenerImpl());
//if you are using java 8 then you can use functional interface like below
//MyCar otherCar = new MyCar(()->{System.out.println("velocity changed....");});
}
}
Listener and its implementation
public interface VelocityListener {
public void doSomething(Velocity velocity);}
public class VelocityListenerImpl implements VelocityListener {
public void doSomething(Velocity velocity) {
while (true) {
if (velocity.isMoving()) {
System.out.println("velocity changed....");
}
}
}}

is actually the oposite, the car need the interface but no need to implement it
public interface MotionListener {
void onObjectMoved(Velocity velocity);
void onObjectStopped();
}
public class MyCar {
private MotionListener myMotionListener;
private void setMotionListener(MotionListener someMotionListener){
myMotionListener= someMotionListener;
}
public void doSomething(){
if(myMotionListener != null){
myMotionListener.onObjectMoved(myVelocity);
}
}
public void notifiyamStop(){
if(myMotionListener != null){
myMotionListener.onObjectStopped();
}
}
// other methods ...
}
public class MyPolice implements MotionListener {
#Override
public void onObjectMoved(Velocity velocity) {
System.out.println("Distance" + velocity.getDistance());
System.out.println("Speed" + velocity.getSpeed());
System.out.println("isMoving" + velocity.isMoving());
// i need here to setup a listener for the boolean value isMoving
}
#Override
public void onObjectStopped() {
}
// other methods ...
}

Apparently, MotionListener is the listener. You need to implement it. Each time MyCar moves, the OnObjectMoved() and OnObjectStopped() methods are called. In those methods, do whatever needs to happen when the car moves or stops, such as recalculating the position.
As far as listeners, the listener will be called by the external entity each time the velocity changes. So, your method simply needs to look at the value and do something with it. I'm guessing Velocity has getters for speed and direction.

Related

Best approach to deal with subclasses in a List with separate dependencies

In doing some restructuring on a project of mine, I've been attempting to better utilise object oriented concepts in my code but I'm not sure how to structure this particular situation:
A method can trigger one of three possible "events", with each event having a dependency on a particular type (Player, Block, World) which needs to happen at runtime as they are deserialised from a file. In an attempt to simplify the execution path I structured it like this so they can all be part of a List which just executes a single method:
public interface IEvent {
void trigger();
}
public class PlayerEvent implements IEvent {
private Player player;
public void passPlayer(Player player){
this.player = player;
}
public void trigger(){
// player does things
}
}
public class BlockEvent implements IEvent {
private Block block;
public void passBlock(Block block){
this.block = block;
}
public void trigger(){
// block does things
}
}
However, since each event is dependent on a Player or Block depending on its type, I would have to iterate over the list and downcast each object using instanceof to pass the relevant dependency.
public void executeEvents(){
for(IEvent event : events){
if(event instanceof PlayerEvent){
((PlayerEvent) event).passPlayer(player);
} else {
((BlockEvent) event).passBlock(block);
}
event.trigger();
}
}
I read that downcasting should never be done under any circumstances, so I've been wondering what alternatives I could use that would follow a similar simple execution path but falls under good OOP practice? Or should I just eliminate the interface altogether and have a separate List for each event type?
I read that downcasting should never be done under any circumstances,
so I've been wondering what alternatives
I would not generalize. Applications/libraries that generate code or use reflection generally may use downcast.
In other cases, downcast should indeed be avoided.
You have multiple ways to achieve your goals without downcasting.
1) Don't manipulate a too broad type in the List. Additionally you could make IEvent a generic interface and generalize passPlayer() and passBlock() in pass() that you will move up in the interface.
The interface could look like :
public interface IEvent<T> {
void trigger();
void pass(T t);
}
And implementation of it could look like :
public class PlayerEvent implements IEvent<Player> {
private Player player;
public void trigger() {
// player does things
}
#Override
public void pass(Player t) {
}
}
Now with a more specific typed List you could write :
private Player player = ...;
public void executeEvents() {
List<IEvent<Player>> events = ...;
for (IEvent<Player> event : events) {
event.pass(player);
}
}
2) Use the visitor pattern to benefit from a double dispatch.
Event -> Visitor -> processing.
Each pass() method become a method of the Visitor.
You could enrich the IEvent interface to add an accept() method that accepts a Visitor :
public interface IEvent {
void trigger();
void accept(Visitor visitor);
}
Here the Visitor interface and implementation :
Visitor interface
public interface Visitor {
void visitBlockEvent(BlockEvent block);
void visitPlayerEvent(PlayerEvent player);
}
Visitor implementation
public class ProcessEventVisitor implements Visitor {
private Player player;
private Block block;
#Override
public void visitBlockEvent(BlockEvent blockEvent) {
// do your processing
}
#Override
public void visitPlayerEvent(PlayerEvent playerEvent) {
// do your processing
}
}
IEvent subclasses delegate now to the Visitor parameter the processing :
public class PlayerEvent implements IEvent{
public void trigger() {
// player does things
}
#Override
public void accept(Visitor visitor) {
visitor.visitPlayerEvent(this);
}
}
And the client code can now look like :
private Player player;
public void executeEvents() {
List<IEvent> events = ...;
ProcessEventVisitor visitor = new ProcessEventVisitor();
for (IEvent event : events) {
event.accept(visitor);
}
}

Java: Design pattern for working with state and inheritance

I will try to explain my problem on cars. I have AbstractCar and the users (developers) of my library will create many their ConcreteCars. This AbstractCar has state and this state is very important for right working of the library! Only the car can control its state (no any Drivers etc). The state changes in methods start/stop at the beginning and at the end of the methods. Besides all cars must implement interface Car.
public enum State{
STARTING, STARTED, STOPPING, STOPPED
}
public interface Car{
public void start();
public void stop();
public State getState();
}
I tried two variants.
Variant 1
public abstract class AbstractCar implements Car{
private State state;
public void setState(State state){...}
public State getState(){...}
}
public class ConcreteCar extends AbstractCar{
#Override
public void start(){
setState(stateK);
...
setState(stateN);
}
#Override
public void stop(){
setState(stateR);
...
setState(stateO);
}
}
At variant 1 the user of the library will have to remember to change the state. If he forgets to do it, then there will be a bug in the code.
Variant 2
public abstract class AbstractCar implements Car{
private State state;
protected void doOnStart(){ }
protected void doOnStop(){ }
public final void start(){
state=...;
doOnStart();
state=...;
}
public final void stop(){
state=...;
doOnStop();
state=...;
}
}
public class ConcreteCar extends AbstractCar{
#Override
protected void doOnStart(){
....
}
#Override
protected void doOnStop(){
...
}
}
In variant 2 the user can't forget about state because it is already outside his control, but if I have many states and many methods in which they can be changed this is not a very good way.
Could anyone advise any pattern or technologies how to solve such problem?
If you want to retain full control over which state the car will be at a given moment and which transitions are allowed, the second approach is the basic pattern to use.
You may modify the way you call the subclass' code (be it by calling an abstract method, or some other kind of callback), but the basic pattern will be the same - your AbstractCar's code will contain the logic of states and transitions, with defined points where "external" code may be called. These are also sometimes referred to as "hooks".
A (perhaps a bit far-fetched) example of such approach is JSF life-cycle where the request goes through a complex workflow and in some given phases (e.g. validation) user-supplied code may be executed - but it has no way to directly set the state of the request.
If you want to allow your users (i.e. subclass authors) to be able to affect the car's state, you can do so in a controlled way by accepting a return value from the callback that affects the following state transition, or in some cases simply by doing proper error-handling:
public final void start(){
state=STARTING;
try {
doOnStart();
state=STARTED;
} catch (RuntimeException e) {
// handle error
state=STOPPED;
}
}
In variant 2 the user can't forget about state because it is already
outside his control
And is it desirable ?
public abstract class AbstractCar implements Car{
...
public final void start(){
state=...;
doOnStart();
state=...;
}
...
}
In the abstract class you determine for the concrete classes the state that they should be used.
It doesn't seem a very flexible solution for concrete classes since a state change should depend on the context that may change in the start() method.
You should use abstract method in AbstractCar to both allow and force concrete classes to choose how define their state such as :
Suppose this concrete class :
public abstract class AbstractCar implements Car{
...
public abstract State getStateBeforeStart();
public abstract State getStateAfterStart();
...
public final void start(){
state = getStateBeforeStart();
doOnStart();
state = getStateAfterStart();
}
...
}
You could also use Javadoc to document correctly the API of your classes and the responsibilities of concrete classes in order to favor a good use of it.
Use a state design pattern. https://sourcemaking.com/design_patterns/state
Keep your AbstractCar as a Context and use it to manage the state of the car.
I do an example as following. Hopefully I understand it correctly.
public interface IState {
public void changeState(Car inContext);
public void doSomething();
}
public interface Car {
enum CarState{
start,
stop,
auto
}
public void setState(CarState state);
}
public class AbstractCar implements Car {
IState m_currentState;
IState startState = new StartState();
IState stopState = new StopState();
IState autoState = new AutoNavigateState();
public AbstractCar() {
m_currentState = stopState;
}
public void start() {
setState(CarState.start);
m_currentState.doSomething();
m_currentState.changeState(this);
}
public void stop() {
setState(CarState.stop);
m_currentState.doSomething();
m_currentState.changeState(this);
}
public void autoNavigate() {
setState(CarState.auto);
m_currentState.doSomething();
m_currentState.changeState(this);
}
public void setState(CarState state) {
if (state == CarState.start) {
m_currentState = startState;
} else if (state == CarState.stop) {
m_currentState = stopState;
} else {
m_currentState = autoState;
}
}
}
public class StartState implements IState {
#Override
public void changeState(Car car) {
car.setState(CarState.stop);
}
#Override
public void doSomething() {
// TODO Auto-generated method stub
}
}
public class StopState implements IState{
#Override
public void changeState(Car car) {
car.setState(CarState.start);
}
#Override
public void doSomething() {
// TODO Auto-generated method stub
}
}
public class AutoNavigateState implements IState{
#Override
public void changeState(Car inContext) {
// TODO Auto-generated method stub
}
#Override
public void doSomething() {
// TODO Auto-generated method stub
}
}

C# equivalent to implement interface inside super keyword in Java [duplicate]

I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :

java 8 event listener/dispatcher using lambdas/method references - how to achieve certain things?

I'm trying to write an event engine in Java using the newly added lambdas. I would very much like it if the following code would work:
public class Test
{
public Test()
{
EventEngine.listen(EventType.THIS, self::thisEventCallback);
EventEngine.listen(EventType.THAT, self::thatEventCallback);
EventEngine.listen(EventType.OTHER, (other) -> other.doX());
}
private void thisEventCallback()
{
// do whatever here
}
private boolean thatEventCallback(SomeObject parameter)
{
return parameter.someCheckOrWhatever();
}
}
As far as I understand, I would have to define a generic empty interface, for example, public interface Listener {// nothing here}, and extend it via various other interfaces for each event type so I can specify different parameters and return types where necassary.
Obviously, that would require casting the callbacks to the specific interface inside the EventEngine's trigger method(s), but I have no problem with that.
However, before that I need to find out how to reference these private methods I have defined to the EventDispatcher.listen method. self::thisEventCallback doesn't work. Is there even a way to do this in Java 8 or is it only possible in Scala?
If not, then what would you suggest as a replacement that does not involve creating a new object for every listener/callback?
EventEngine.listen(EventType.THIS, this::thisEventCallback);
EventEngine.listen(EventType.THAT, this::thatEventCallback);
EventEngine.listen(EventType.OTHER, (other) -> other.doX());
So this instead of self.
And you need functional interfaces with one abstract method having the same signature as the callback.
public interface THISInterface {
public void thisEventCallback();
}
public interface THATInterface {
public boolean thatEventCallback(SomeObject parameter)
}
class EventEngine {
public void listen(Type t, THISInterfcace thisCallback) {
thisCallback.thisEventCallback();
}
public void listen(Type t, THATInterfcace thatCallback) {
boolean ok = thatCallback.thatEventCallback();
}
...
}
However there are already many functional interfaces predefined, which you should need to learn. For instance here, one would not need own interfaces.
class EventEngine {
public void listen(Type t, Consumer<Void> thisCallback) {
thisCallback.accept();
}
public void listen(Type t, Predicate<Void> thatCallback) {
boolean ok = thatCallback.test();
}
Whether the above is correct, I am not sure (at the moment deep in java 6 - sigh).
Instead of creating sub-interfaces adding new methods to a base interface you can define a conventional listener interface (like, say MouseListener) having multiple call-back methods and create sub-interfaces overriding all but one method with empty default methods for the sole purpose of allowing lambda implementations of the remaining single abstract method. They replace what classes like MouseAdapter did for previous Java versions (when using anonymous inner classes):
interface AllPurposeListener {// the only one our engine uses internally
void caseOne(int arg);
void caseTwo(String arg);
}
interface CaseOneListener extends AllPurposeListener {
#Override public default void caseTwo(String arg) {}
}
interface CaseTwoListener extends AllPurposeListener {
#Override public default void caseOne(int arg){}
}
// Of course, I over-simplify the engine’s listener registry here
AllPurposeListener listener;
public void listen(AllPurposeListener l) {
listener=l;
}
public void listen(CaseOneListener l) {
listener=l;
}
public void listen(CaseTwoListener l) {
listener=l;
}
private void foo(int i) { }
private void bar(String s) { }
void doRegistration() {
listen(this::foo);// register for case one
listen(this::bar);// register for case two
listen(new AllPurposeListener() { // for all cases
public void caseOne(int arg) {
}
public void caseTwo(String arg) {
}
});
}

Events with different types and data

I am writing a library in Java, which throws an event of different types with differing data depending on the type.
For example, here is the extended EventObject:
public class FooEvent extends EventObject {
private final int eventType;
private final Object fooEventObject;
public FooEvent(int type, Object obj){/*...*/}
public int getEventType() {/*...*/}
public int getEventObject() {/*...*/}
}
And here is how I my listener currently looks like:
FooEventListener listener = new FooEventListener() {
#Override
public void onDataChange(FooEvent event) {
switch(event.getEventType()) {
case EVENT_TYPE_BAR:
Bars bar = (Bars)event.getEventObject();
/*work with Bar object...*/
break;
case EVENT_TYPE_GOO:
Goo goo = (Goo)event.getEventObject();
/*work with Goo object...*/
break;
/* etc ...*/
}
}
}
I would like to know if this is the right way of solving this problem (although I doubt it is, since the user of the library would need to know what type to cast to) wherein I have different event types with objects and I do not want to go and make a different event & listener for each one.
Guava's EventBus provides a slightly different approach that can handle multiple event types.
There is unfortunately no easy solution to have a type safe event system with different types. You either have to have 1 listener / publishing implementation per type of you need to teach one side about all the event types that exist.
There is a way to remove the need for instanceof or switch (type) and casting though: the Visitor Pattern
The pattern uses the fact that event objects know their own type which means they can call the right method. The downside is that you need a listener interface that contains all the types.
public class Test {
abstract static class EventObject {
protected abstract void deliver(EventListener listener);
}
static class AEvent extends EventObject {
#Override
protected void deliver(EventListener listener) {
listener.onAEvent(this);
}
}
static class BEvent extends EventObject {
#Override
protected void deliver(EventListener listener) {
listener.onBEvent(this);
}
}
interface EventListener {
void onAEvent(AEvent event);
void onBEvent(BEvent event);
// ...
}
private static final EventListener LISTENER = new EventListener() {
#Override
public void onBEvent(BEvent event) {
System.out.println("Got B Event! " + event);
}
#Override
public void onAEvent(AEvent event) {
System.out.println("Got A Event! " + event);
}
};
private static void notifyListeners(EventObject event) {
event.deliver(LISTENER);
}
public static void main(String[] args) {
notifyListeners(new AEvent());
notifyListeners(new BEvent());
}
}
A better way to solve this is with generics.
public class FooEvent<T> extends EventObject {
private final T fooEventObject;
public FooEvent(T obj){/*...*/}
public T getEventObject() {/*...*/}
}
//usage
SomeType object = new SomeType();
new FooEvent<SomeType>(object);
I think it's a way to go, but not the cleanest way. You should create an abstract class
public abstract class AbstractEventType<T> extends EventObject {}
and extend from that:
public abstract class FooEvent extends AbstractEventType<Foo> {}
public abstract class BarEvent extends AbstractEventType<Bar> {}
Then you need to fire different events and also have different event listeners based on the type:
public interface FooEventListener {
public void onFooChange(FooEvent fooEvent);
}
etc.
If you want to stick with only one event type then you could at least move the code to determine the type to your framework and avoid pollution of the "business" code, by creating one handler method per type, e.g.
public interface MyEventListener {
public void onFooChange(EventType<Foo> eventType);
public void onBarChange(EventType<Bar> eventType);
}

Categories