I want to implement FSM like below
First Level Most basic State is BASE_STATE. All
states derive from BASE_STATE.
Second Level, WAITING_STATE,
RUNNING_STATE, END_STATE, ... so on
(Derived from BASE_STATE. No new
functionality)
Third level, There are 2 groups
states (ACTIVE and PASSIVE),
One-on-one matching for all second level states
like
ACTIVE_WAITING_STATE , ACTIVE_RUNNING_STATE , ACTIVE_END_STATE, so on
PASSIVE_WAITING_STATE, PASSIVE_RUNNING_STATE, PASSIVE_END_STATE, so on
most functionalities are common for ACTIVE and PASSIVE states, just some small functions overrided. There is no problem until here. Problem is, All third level group have common functions. I mean, For example I have to implement 2 different increment() function one of is ACTIVE_xxx_STATEs, another one is PASSIVE_xxx_STATEs. How to do this without re-written for all states (eg. ACTIVE_WAITING_STATE , ACTIVE_RUNNING_STATE , ACTIVE_END_STATE, and also PASSIVE states)
To clearify my questions, my ugly sol'n. Problem is increment functions is same and re-written for all ActivexxxState (and also PassiveXXXState).
public class BaseState {
// Lots of functions
}
public class WaitingState extends BaseState{
// Lots of functions
}
public class RunningState extends BaseState{
// Lots of functions
}
public class EndState extends BaseState{
// Lots of functions
}
public Class ActiveWaitingState extends WaitingState {
// Few unique functions
private void increment() {
System.out.println("increment active");
}
}
public Class ActiveRunningState extends RunningState {
// Few unique functions
private void increment() {
System.out.println("increment active");
}
}
public Class ActiveEndState extends EndState {
// Few unique functions
private void increment() {
System.out.println("increment active");
}
}
public Class PassiveWaitingState extends WaitingState {
// Few unique functions
private void increment() {
System.out.println("increment passive");
}
}
public Class PassiveRunningState extends RunningState {
private void increment() {
System.out.println("increment passive");
}
}
public Class PassiveEndState extends EndState {
private void increment() {
System.out.println("increment passive");
}
}
I would make increment() a protected method in BaseState so it is implemented once.
I have written an article on using enums to build a state machine. This can avoid the need to create classes everywhere for each state and still support some inheritance.
In answer to your comment.
abstract class BaseState {
public abstract boolean isPassive();
public boolean increment() {
System.out.println("increment "+(isPassize() ? "passive" : "active");
}
}
class PassiveState {
public boolean isPassive() { return true; }
}
If you don't want to have multiple isPassive methods you could assume a class naming convention
public boolean isPassive() { return getClass().getSimpleName().startsWith("Passive"); }
I'm not sure to have fully understand your question. Anyway, I'll suggest you to model active/passive state like a property in your class rather then use inheritance.
Make your hierarchy something like:
public class BaseState {
boolean active; //active or passive
}
public class WaitingState extends BaseState {
}
...
If you share common behaviour in your state machine you have two possibilities to implement that.
1) You can add the common implementation to the base state, so it can be called by any state implementation that inherits from the base state. The visibility of these methods would be protected.
2) A better solution in my oppinion is that you move the common behaviour into its own class that is not related to the states class hierarchy at all.
So you can think about a strategy class that implements the common behaviour and is referenced by the base class and can be called by any state.
The second solution is better because it increases the testability of both, the state machine and the strategy class.
Related
I do have a service which needs to handle two types of meal.
#Service
class MealService {
private final List<MealStrategy> strategies;
MealService(…) {
this.strategies = strategies;
}
void handle() {
var foo = …;
var bar = …;
strategies.forEach(s -> s.remove(foo, bar));
}
}
There are two strategies, ‘BurgerStrategy’ and ‘PastaStrategy’. Both implements Strategy interface with one method called remove which takes two parameters.
BurgerStrategy class retrieves meals of enum type burger from the database and iterate over them and perform some operations. Similar stuff does the PastaStrategy.
The question is, does it make sense to call it Strategy and implement it this way or not?
Also, how to handle duplications of the code in those two services, let’s say both share the same private methods. Does it make sense to create a Helper class or something?
does it make sense to call it Strategy and implement it this way or not
I think these classes ‘BurgerStrategy’ and ‘PastaStrategy’ have common behaviour. Strategy pattern is used when you want to inject one strategy and use it. However, you are iterating through all behaviors. You did not set behaviour by getting one strategy and stick with it. So, in my honour opinion, I think it is better to avoid Strategy word here.
So strategy pattern would look like this. I am sorry, I am not Java guy. Let me show via C#. But I've provided comments of how code could look in Java.
This is our abstraction of strategy:
public interface ISoundBehaviour
{
void Make();
}
and its concrete implementation:
public class DogSound : ISoundBehaviour // implements in Java
{
public void Make()
{
Console.WriteLine("Woof");
}
}
public class CatSound : ISoundBehaviour
{
public void Make()
{
Console.WriteLine("Meow");
}
}
And then we stick with one behaviour that can also be replaced:
public class Dog
{
ISoundBehaviour _soundBehaviour;
public Dog(ISoundBehaviour soundBehaviour)
{
_soundBehaviour = soundBehaviour;
}
public void Bark()
{
_soundBehaviour.Make();
}
public void SetAnotherSound(ISoundBehaviour anotherSoundBehaviour)
{
_soundBehaviour = anotherSoundBehaviour;
}
}
how to handle duplications of the code in those two services, let’s say both share the same private methods.
You can create one base, abstract class. So basic idea is to put common logic into some base common class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete case. Let me show an example.
An abstract class which has common behaviour:
public abstract class BaseMeal
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{
// put here code that can be shared among subclasses to avoid code duplication
}
public abstract void UnCommonBehaviourShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class BurgerSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class PastaSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
I design my game application and face some troubles in OOP design.
I want to know some patterns which can help me, because java have not any multiple extends option. I will describe my problem below, and also explain why multiple interface doesn't help me at all. Lets go.
What we want is "class is set of features". By feature I mean construction like:
field a;
field b;
field c;
method m1(){
// use, and change fields a,b,c;
}
method m2(){
// use, and change fields a,b,c;
}
//etc
So, basically the feature is a set of methods and corresponding fields. So, it's very close to the java interface.
When I talk that class implemets "feature1" I mean that this class contains ALL "feature needed" fields, and have realisation of all feature related methods.
When class implements two features the tricky part begins. There is a change, that two different features contains similar fields (names of this fields are equal). Let the case of different types for such fields will be out of scope. What I want - is "feature naming tolerance" - so that if methodA() from feature A change the field "common_field", the methodB from feature B, that also use "common_field" as field will see this changes.
So, I want to create a set of features (basically interfaces) and their implementations. After this I want to create classes which will extends multiple features, without any copy-paste and other crap.
But I can't write this code in Java:
public static interface Feature1 {
public void method1();
}
public static interface Feature2 {
public void method2();
}
public static class Feature1Impl implements Feature1 {
int feature1Field;
int commonField;
#Override
public void method1() {
feature1Field += commonField;
commonField++;
}
}
public static class Feature2Impl implements Feature2 {
int feature2Field;
int commonField;
#Override
public void method2() {
commonField++;
}
}
public static class MyFeaturedClass extends Feature1Impl, Feature2Impl implements Feature1, Features2 {
}
So, as you can see the problem are really complex.
Below I'll describe why some standart approaches doesn't work here.
1) Use something like this:
public static class MyFeaturesClass implements Feature1,Feature2{
Feature1 feature1;
Feature2 feature2;
#Override
public void method2() {
feature2.method2();
}
#Override
public void method1() {
feature1.method1();
}
}
Ok, this is really nice approach - but it does not provide "feature field name tolerance" - so the call of method2 will not change the field "commonField" in object corresponding the feature1.
2) Use another design. For what sake you need such approach?
Ok. In my game there is a "unit" concept. A unit is MOVABLE and ALIVE object.
Movable objects has position, and move() method. Alive objects has hp and takeDamage() and die() methods.
There is only MOVABLE objects in my game, but this objects isn't alive.
Also, there is ALIVE objects in my game, but this objects isn't movable (buildings for example).
And when I realize the movable and alive as classes, that implements interfaces, I really don't know from what I should extends my Unit class. In both cases I will use copy-paste for this.
The example above is really simple, actually I need a lot of different features for different game mechanics. And I will have a lot of different objects with different properties.
What I actually tried is:
Map<Field,Object> fields;
So any object in my game has such Map, and to any object can be applied any method. The realization of method is just take needed fields from this map, do its job and change some of them. The problem of this approach is performance. First of all - I don't want to use Double and Interger classes for double and int fields, and second - I want to have a direct accsess to the fields of my objects (not through the map object).
Any suggestions?
PS. What I want as a result:
class A implements Feature1, Feature2, Feature3, Feature4, Feature5 {
// all features has corresponding FeatureNImpl implementations;
// features 1-2-3 has "shared" fields, feature 3-4 has, features 5-1 has.
// really fast implementation with "shared field tolerance" needed.
}
One possibility is to add another layer of interfaces. XXXProviderInterface could be defined for all possible common fields, that define a getter and setter for them.
A feature implementation class would require the needed providers in the constructor. All access to common fields are done through these references.
A concrete game object class implementation would implement the needed provider interfaces and feature interfaces. Through aggregation, it would add the feature implementations (with passing this as provider), and delegate the feature calls to them.
E.g.
public interface Feature1 {
void methodF1();
}
public interface Feature2 {
void methodF2();
}
public interface FieldAProvider {
int getA();
void setA(int a);
}
public class Feature1Impl implements Feature1 {
private FieldAProvider _a;
Feature1Impl(FieldAProvider a) {
_a = a;
}
void methodF1() {
_a.setA(_a.getA() * 2);
}
}
// Similar for Feature2Impl
public class GameObject implements Feature1, Feature2, FieldAProvider
{
int _fieldA;
Feature1 _f1;
Feature2 _f2;
GameObject() {
_f1 = new Feature1Impl(this);
_f2 = new Feature2Impl(this);
}
int getA() {
return _fieldA;
}
void setA(int a) {
_fieldA = a;
}
void methodF1() {
_f1.methodF1();
}
void methodF2() {
_f2.methodF2();
}
}
However, I don't think this is an optimal solution
I have a class which has a method called connect(par1, par2, par3), par3 is an interface/listenr.
To provide par3 i can do as follows:
connect(par1, par2, asynchCallBack2 );
private class asynchCallBack2 implements MqttCallback {
...
...
}
OR:
connect(par1, par2, asynchCallBack2 );
MqttCallback asynchCallBack2 = new MqttCallback {
...
...
}
And in either cases, every thing works jus fine. So what is the difference and in which scenarios each of the implementation is used?
In one case (i.e. where you say implements) you are defining full fledge method local class.
While for the other you are defining anonymous class which is similar to the one where you said implements. Just that you aren't defining the name and say like implements myinterface which is implicit to compiler.
It's just the way you define your class, nothing changes in terms of functionality.
The difference is requirement and handling exceptional cases ,Hope this pseudo code clears it for you
interface Engine{
public void start();
}
private class FerrariEngine implements Engine{
public void preStartRoutine(){}
public void Start(){}
}
private class Main{
private void main(){
Engine engine=getEngine();
if(engine instanceOf FerrariEngine){
((FerrariEngine)engine).preStartRoutine();
}
engine.start();
}
private Engine getEngine(){
if(System==Generic)
return new Engine{
#override
public void start(){
//Do start
}
}
else if(System==Ferrari)
return new FerrariEngine();
}
}
As a general principle,If u need more functionality whilst still being able to adhere to older version, creating an instance of an extended version of that class instead of making an anonymous instance makes sense.
I was wondering how would someone justify creating a GameManager while having the Single Responsibility Principle (SRP) in mind. concrete example: GameManager of a memory game (with the cards that you have to match). It obviously have many responsibilities: tracking of who's turn is it, switching between the turns, tracking when the game is finished, who the winner is and more...
When in doubt about exceeding object responsabilities. There is a concept related to SRP, cohesion, which is quite objective. In Konamiman's answer, the GameManager is 100% cohesive. It means all dependencies (instance fields) are used in all public methods.
0% would be the opposite:
class GameManager {
private int anInt;
private object aObj;
public void Foo() {
// Do anything but using anInt or aObj
}
}
If you find several cohesive components inside your object:
class GameManager {
private T1 obj1;
private T2 obj2;
public void Foo() {
T1.F1();
}
public void Goo() {
T2.G1();
}
}
The class should be split in two:
class GameManagerFoo {
private T1 obj1;
public void Foo() {
T1.F1();
}
}
class GameManagerGoo {
public void Goo() {
T2.G1();
}
}
Nice point #Jackl56: About property setters and getters you have 2 options. You could not take them into account or you could consider they lower your cohesion but to an acceptable level.
The key is that if you do things properly, the GameManager class will not directly have all the responsibilities you have mentioned. Instead, it will delegate these responsibilities into other classes, that will be passed to it by using some form of dependency injection. So you can say that the GameManager class has a single responsibility: to coordinate the work of the other classes; and has one single reason to change: to accommodate a change in the game logic that requires a new class to participate or to change the order of the interaction between classes.
A very simple example (sorry, C# syntax, but you get the idea):
public class GameManager
{
//constructor - note that the parameter types are interfaces, not classes
public GameManager(
IPlayerManager playerManager,
ITurnManager turnManager)
{
this.playerManager = playerManager;
this.turnManager = turnManager;
}
public void DoNextTurn()
{
var nextPlayer = playerManager.GetNextPlayer();
turnManager.ProcessTurn(nextPlayer);
//etc...
}
}
class A extends ApiClass
{
public void duplicateMethod()
{
}
}
class B extends AnotherApiClass
{
public void duplicateMethod()
{
}
}
I have two classes which extend different api classes. The two class has some duplicate
methods(same method repeated in both class) and how to remove this duplication?
Edit
Both ApiClass and AnotherApiClass are not under my control
Depending on what the code is you could do something like:
public class Util
{
public static void duplicateMethod()
{
// code goes here
}
}
and then just have the other two duplicateMethods call that one. So the code would not be duplicated, but the method name and the call to the Util.duplicateMethod would be.
If the code in the Util.duplicateMethod needed to access instance/class variables of the A and B class it wouldn't work out so nicely, but it could potentially be done (let me know if you need that).
EDIT (based on comment):
With instance variables it gets less pretty... but can be done. Something like:
interface X
{
int getVar();
void setVar(A a);
}
class A
extends ApiClass
implements X
{
}
class B
extends AnotherApiClass
implements X
{
}
class Util
{
public static void duplicateMethod(X x)
{
int val = x.getVal();
x.setVal(val + 1);
}
}
So, for each variable you need to access you would make a method for get (and set if needed). I don't like this way since it make the get/set methods public which may mean you are making things available that you don't want to be available. An alternative would be to do something with reflection, but I'd like that even less :-)
Sounds like a case for the "Strategy Pattern".
class A extends ApiClass {
private ClassContainingDupMethod strategy;
}
class N extends AnotherApiClass {
private ClassContainingDupMethod strategy;
public methodCallingDupMethod(){
strategy.dupMethod();
}
}
class ClassContainingDupMethod{
public dupMethod(){;}
}
Or is the dupMethod inherted from the Api classes?
Duplicate methods that rely on member variables imply duplicate member variables, too - and that starts to smell like too-large classes. What would those specific member variables, with the method(s), look like, if you were to extract them into their own class, and then compose that class into your other classes? Prefer composition over inheritance.
class BaseApiClass
{
public void duplicateMethod()
{
}
}
class ApiClass extends BaseApiClass
{
}
class AnotherApiClass extends BaseApiClass
{
}
class A extends ApiClass
{
}
class B extends AnotherApiClass
{
}
You need to combine the classes into one object and then all classes using th other two classes, modify their code to use the single class.