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
}
}
Related
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.
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);
}
}
I have a number of classes that define a method, and I want to execute some code (say, some "prologue" and "epilogue") around that method:
public interface Thing {
public void stuff();
public void callStuff();
}
public abstract class Something implements Thing {
public abstract void stuff();
public void callStuff() {
... // common prologue
//try {
stuff();
//} finally {
... // common epilogue
//}
}
}
public class A extends Something {
public void stuff() { ... }
}
public class B extends Something {
public void stuff() { ... }
}
public class Wrapper extends Thing {
private Thing t;
Wrapper(Thing thing) { t = thing; }
public void stuff() { t.stuff(); }
public void callStuff() { t.callStuff(); }
}
// Use:
Something s = ...;
s.callStuff();
You see that the idea is that subclasses will redefine stuff() while the clients will invoke callStuff(). Nevertheless, in some rare cases one has to call stuff(), see Wrapper above.
Something like that we see in the Thread class (since JDK 1.0), child classes redefine run() but the clients invoke start().
How do I prevent clients from calling stuff() directly?
EDIT
protected does not work here because the "clients" really are children of Something coded by another team. #Deprecated would work, but stuff() is not really deprecated, and everyone knows what "deprecated" is, so I cannot redefine the meaning of #Deprecated.
Ideally, the compilation should fail unless an explicit directive is given to ignore the problem.
I have an interface called Worker which I want to expose so that the end-user can simply call:
Worker w = WorkerFactory.createInstance();
w.mainBit();
How can I prevent classes which extend my AbstractWorker class from providing their own implementation of the mainBit method?
This is the structure I have so far:
interface Worker {
void mainBit();
}
class WorkerFactory {
public static Worker createInstance() {
return new WorkerImpl();
}
}
abstract class AbstractWorker implements Worker {
#Override
public void mainBit() {
this.doThing1();
this.doThing2();
}
public abstract void doThing1();
public abstract void doThing2();
}
class WorkerImpl extends AbstractWorker {
#Override
public void doThing1() {
}
#Override
public void doThing2() {
}
#Override
public void mainBit() {
// I don't want classes to override this functionality
}
}
You can do that by making the method final.
Use the final keyword.
public final void mainbit ()
...
Mark the method as final, which prevents overriding:
public final void mainBit()
If you want to always use the AbstractWorker's mainBit, make it final in this class. This way, the subclasses won't override it.
Mark it final inside you abstract class (in Java). No other subclass will be allowed to override it.
Consider the simple example below of implementing a method in an Enum. One problem with this method is that, when you have a lot of enum instances, you visually can no longer see them all at once, as a list. That is, if we had many toys, I would like to see "DOLL, SOLDIER, TEDDYBEAR, TRAIN, ETC", together, in one long list, and then after that list I could implement any needed methods, e.g. methods that are abstract in the enum itself.
Is there any way to do this? Or do you have to implement the methods when you declare the individual enum instances, as in the example below?
public enum Toy {
DOLL() {
#Override public void execute() {
System.out.println("I'm a doll.");
}
},
SOLDIER() {
#Override public void execute() {
System.out.println("I'm a soldier.");
}
};
//abstract method
public abstract void execute();
}
One way that comes to mind is to leave the implementation of the abstract methods to separate implementation classes, something like:
interface ToyBehaviour {
void execute();
}
public enum Toy {
DOLL(new DollBehaviour()),
SOLDIER(new SoldierBehaviour());
private final ToyBehaviour behaviour;
Toy(ToyBehaviour impl) {
behaviour = impl;
}
public void execute() {
behaviour.execute();
}
}
class DollBehaviour implements ToyBehaviour {
public void execute() {
System.out.println("I'm a doll.");
}
}
This setup would allow you to create behaviour classes in separate files in the case that your implementation has enough complexity to warrant separation.
In the case that the implementation is simple enough to include it into the one enum class, you can put the interface and behaviour classes as children of the enum class:
public enum Toy {
// enum values
DOLL(new DollBehaviour()),
SOLDIER(new SoldierBehaviour());
private final ToyBehaviour behaviour;
Toy(ToyBehaviour impl) {
behaviour = impl;
}
public void execute() {
behaviour.execute();
}
// behaviour interface
interface ToyBehaviour {
void execute();
}
// behaviour implementation (sub)classes
static class DollBehaviour implements ToyBehaviour {
public void execute() {
System.out.println("I'm a doll.");
}
}
// etc ...
}
I would probably opt for the first implementation myself, unless the hierarchy of implementation classes is very trivial.
If you want more compact enum declarations, the only ways I can think of to do it are :
if you can construct your methods out of initializer variables:
public enum Toy {
DOLL("doll"),SOLDIER("soldier");
private Toy(String name){ this.name=name;}
public void execute(){ System.out.println("I'm a "+name );}
}
or, slightly more complicated, kind of the same with functions, if the behavior is more complex -
abstract class SomeToyMethod {
abstract void execute();
public SomeToyMethod DOLL_METHOD = new SomeToyMethod(){
public void execute(){ System.out.println("I'm a doll");})
public SomeToyMethod SOLDIER_METHOD = new SomeToyMethod(){
public void execute(){ System.out.println("I'm a soldier");})
public enum Toy {
DOLL(SomeToyMethod,DOLL_METHOD),SOLDIER(SomeToyMethod.SOLDIER_METHOD);
private Toy(SomeToyMethod method){ this.method=method;}
public void execute(){ method.execute();}
}
You could try something like:
public enum Toy {
DOLL,
SOLDIER,
ANOTHER_TOY;
public static void execute(Toy toy) {
switch(toy) {
case DOLL:
System.out.println("I'm a doll.");
break;
case SOLDIER:
System.out.println("I'm a soldier.");
break;
case ANOTHER_TOY:
System.out.println("I'm another toy.");
break;
}
}
}
Not very pretty but it keeps your enum declarations together.