|
3 | 3 | import java.util.ArrayList; |
4 | 4 | import java.util.List; |
5 | 5 |
|
| 6 | +/** |
| 7 | + * |
| 8 | + * When a message with a parameter is sent to an object, the resultant behaviour is defined by the |
| 9 | + * implementation of that method in the receiver. Sometimes the behaviour must also be determined |
| 10 | + * by the type of the parameter. |
| 11 | + * |
| 12 | + * One way to implement this would be to create multiple instanceof-checks for the methods parameter. |
| 13 | + * However, this creates a maintenance issue. When new types are added we would also need to change |
| 14 | + * the method's implementation and add a new instanceof-check. This violates the single responsibility |
| 15 | + * principle - a class should have only one reason to change. |
| 16 | + * |
| 17 | + * Instead of the instanceof-checks a better way is to make another virtual call on the parameter |
| 18 | + * object. This way new functionality can be easily added without the need to modify existing |
| 19 | + * implementation (open-closed principle). |
| 20 | + * |
| 21 | + * In this example we have hierarchy of objects (GameObject) that can collide to each other. Each |
| 22 | + * object has its own coordinates which are checked against the other objects' coordinates. If |
| 23 | + * there is an overlap, then the objects collide utilizing the Double Dispatch pattern. |
| 24 | + * |
| 25 | + */ |
6 | 26 | public class App { |
7 | 27 |
|
8 | 28 | public static void main( String[] args ) { |
| 29 | + // initialize game objects and print their status |
9 | 30 | List<GameObject> objects = new ArrayList<>(); |
10 | 31 | objects.add(new FlamingAsteroid(0, 0, 5, 5)); |
11 | 32 | objects.add(new SpaceStationMir(1, 1, 2, 2)); |
12 | 33 | objects.add(new Meteoroid(10, 10, 15, 15)); |
13 | 34 | objects.add(new SpaceStationIss(12, 12, 14, 14)); |
14 | | - |
15 | 35 | objects.stream().forEach(o -> System.out.println(o)); |
16 | 36 | System.out.println(""); |
17 | 37 |
|
| 38 | + // collision check |
18 | 39 | objects.stream().forEach(o1 -> objects.stream().forEach(o2 -> { if (o1 != o2 && o1.intersectsWith(o2)) o1.collision(o2); } )); |
19 | 40 | System.out.println(""); |
20 | 41 |
|
| 42 | + // output eventual object statuses |
21 | 43 | objects.stream().forEach(o -> System.out.println(o)); |
22 | 44 | System.out.println(""); |
23 | 45 | } |
|
0 commit comments