I Have a specific behaviour which i want to abstract out in my class.
I See two ways how i can do this.
Option 1 : The behaviour can be overridden by the conventional subclassing of 'SomeClass'.
Class SomeCalss{
public Output behaviour(Input){
//overriden behaviour
}
}
Class SomeOtherClass extends SomeCalss{
public Output behaviour(Input){
//overriden behaviour
}
}
Option 2 : The behaviour can be specified by Plugging in the functional definition from outside
Class SomeCalss{
public Output behaviour(Function<Input,Output> function, Input){
//Functional paradigm
}
}
No Subclassing is needed in 'Option 2'.
Question : (Edit)
While Option 2 gives you flexibility, it forces client code to specify the Function argument, which you will probably want to avoid.
Your goal is to provide clients with a simple interface (behaviour(input)) and hide everything you can- so that clients stay independent from your code.
Option 3 would be
interface Behaves { public Output behaviour(Input i); }
class Behaviour1 implements Behaves {
public Output behaviour(Input i){ /* your implementation here*/ }
}
class FunctionBasedBehaviour implements Behaves {
private final Function<Input,Output> f;
public FunctionBasedBehaviour (Function<Input,Output> f) {this.f=f;}
public Output behaviour(Input i){ return f(i); }
}