lundi 20 juillet 2020

Design pattern to reuse the existing interface implementation in java

Suppose i have an interface

    public interface Action<T> {
        void doWork(T t);
    }

Now this class is implemented by

    public class DefaultAction implements Action<String> {
        @Override
        public void doWork(String s) {
            System.out.println(s);
        }
    }

Now i have a flow which accepts action

public abstract class Flow<T> {

    void execute(T t){
        Action<T> action = getAction();
        action.doWork(t);
    }

    abstract Action<T> getAction();
}

so i have flow that accepts double

public class AnotherActionFlow extends Flow<Double> {

    @Override
    Action<Double> getAction() {
        return new AnotherActionSet();
    }
}

which in turn uses the default action

public class AnotherActionSet implements Action<Double> {

    DefaultAction defaultAction;

    @Override
    public void doWork(Double aDouble) {
        defaultAction.doWork(String.valueOf(aDouble));
    }
}

So in this case i have to always update the AnotherActionSet method whenever the action interface changes

Is their any workaround so that i can have the common logic to convert the double to string and then use the DefaultAction

Can any pattern help to convert the AnotherActionSet to DefaultAction in which i only specify String.valueOf(aDouble) so the values can be passed to DefaultAction instead of writing same thing for every method

Summary

I want to reuse use the logic inside the DefaultAction for other actions which are a wrapper around the DefaultAction

Aucun commentaire:

Enregistrer un commentaire