Created
November 4, 2017 06:30
-
-
Save praveer09/be7787c35a5c62df09b405a3b41c1b0a to your computer and use it in GitHub Desktop.
Example showing how existing interfaces can be extended to provide additional features by using the Function interface, introduced in Java 8, without breaking existing code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.Function; | |
public class ExtensionUsingJava8Funtion { | |
public static void main(String[] args) { | |
SomeInterface someInterface = new SomeInterfaceImpl(); | |
demoAdaptingInput(someInterface); | |
demoAdaptingOutput(someInterface); | |
demoAdaptingBothInputAndOutput(someInterface); | |
} | |
private static void demoSimpleUsage(SomeInterface someInterface) { | |
SomeInput someInput = new SomeInput(); | |
SomeOutput someOutput = someInterface.transform(someInput); | |
} | |
private static void demoAdaptingInput(SomeInterface someInterface) { | |
SomeOtherInput someOtherInput = new SomeOtherInput(); | |
SomeOutput someOutput = someInterface | |
.compose(SomeOtherInput::toSomeInput) | |
.apply(someOtherInput); | |
} | |
private static void demoAdaptingOutput(SomeInterface someInterface) { | |
SomeInput someInput = new SomeInput(); | |
SomeOtherOutput someOtherOutput = someInterface | |
.andThen(SomeOtherOutput::fromSomeOutput) | |
.apply(someInput); | |
} | |
private static void demoAdaptingBothInputAndOutput(SomeInterface someInterface) { | |
SomeOtherInput someOtherInput = new SomeOtherInput(); | |
SomeOtherOutput someOtherOutput = someInterface | |
.compose(SomeOtherInput::toSomeInput) | |
.andThen(SomeOtherOutput::fromSomeOutput) | |
.apply(someOtherInput); | |
} | |
// ****************** Core Classes ********************** | |
interface SomeInterface extends Function<SomeInput, SomeOutput> { | |
default SomeOutput apply(SomeInput someInput) { | |
return transform(someInput); | |
} | |
SomeOutput transform(SomeInput someInput); | |
} | |
static class SomeInterfaceImpl implements SomeInterface { | |
@Override | |
public SomeOutput transform(SomeInput someInput) { | |
return new SomeOutput(); | |
} | |
} | |
static class SomeInput { | |
} | |
static class SomeOutput { | |
} | |
// ****************** Other Classes *********************** | |
static class SomeOtherInput { | |
SomeInput toSomeInput() { | |
return new SomeInput(); | |
} | |
} | |
static class SomeOtherOutput { | |
static SomeOtherOutput fromSomeOutput(SomeOutput someOutput) { | |
return new SomeOtherOutput(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment