Java Reference
In-Depth Information
Minimal interfaces with orthogonal functionalities
Let's say you need to define several shapes with different characteristics for the game you're
creating. Some shapes should be resizable but not rotatable; some should be rotatable and
moveable but not resizable. How can you achieve great code reuse?
You can start by defining a standalone Rotatable interface with two abstract methods,
setRotationAngle and getRotationAngle. The interface also declares a default rotateBy method
that can be implemented using the setRotationAngle and get-RotationAngle methods as follows:
This technique is somewhat related to the template design pattern where a skeleton algorithm is
defined in terms of other methods that need to be implemented.
Now, any class that implements Rotatable will need to provide an implementation for
setRotationAngle and getRotationAngle but will inherit the default implementation of rotateBy
for free.
Similarly, you can define two interfaces, Moveable and Resizable, that you saw earlier. They
both contain default implementations. Here's the code for Moveable:
public interface Moveable {
int getX();
int getY();
void setX(int x);
void setY(int y);
default void moveHorizontally(int distance){
setX(getX() + distance);
}
default void moveVertically(int distance){
setY(getY() + distance);
}
 
Search WWH ::




Custom Search