Skip to contentMethod: changeName(String)
      1: package de.fhdw.gaming.ipspiel23.c4.domain.impl;
2: 
3: import java.util.Optional;
4: import java.util.function.Consumer;
5: 
6: import de.fhdw.gaming.core.domain.GameException;
7: import de.fhdw.gaming.ipspiel23.c4.domain.IC4Player;
8: import de.fhdw.gaming.ipspiel23.c4.domain.IC4PlayerBuilder;
9: import de.fhdw.gaming.ipspiel23.c4.strategies.IC4Strategy;
10: 
11: /**
12:  * The default implementation of {@link IC4PlayerBuilder}.
13:  */
14: final class C4PlayerBuilder implements IC4PlayerBuilder {
15: 
16:     /**
17:      * The token that uniquely identifies the player.
18:      */
19:     private final int token;
20:     
21:     /**
22:      * The name of the player.
23:      */
24:     private Optional<String> name;
25: 
26:     /**
27:      * The hook that is used to inject the strategy into the player object when the player is added to the game.
28:      */
29:     private Consumer<IC4Strategy> playerStrategyHook; 
30: 
31:     /**
32:      * Creates a new instance of {@link C4PlayerBuilder}.
33:      * 
34:      * @param id The token that uniquely identifies the player.
35:      */
36:     C4PlayerBuilder(final int id) {
37:         this.token = id;
38:         this.name = Optional.empty();
39:     }
40: 
41:     /**
42:      * Sets the hook that is used to inject the strategy into the player object when the player is added to the game.
43:      * 
44:      * @param value The hook that is used to inject the strategy into the player object when the player is 
45:      * added to the game.
46:      */
47:     void setPlayerStrategyHook(final Consumer<IC4Strategy> value) {
48:         this.playerStrategyHook = value;
49:     }
50: 
51:     /**
52:      * Injects the strategy into the player object.
53:      * 
54:      * @param strategy The strategy that is injected into the player object.
55:      */
56:     void injectPlayerStrategyUsingHook(final IC4Strategy strategy) {
57:         if (playerStrategyHook == null) {
58:             throw new IllegalStateException("Attempted to inject strategy into player object before "
59:                 + "hook was configured!");
60:         }
61:         // we don't want to expose the strategy setter to anyone, so it's done via this
62:         // hook kindly provided to us by the C4Player constructor.
63:         playerStrategyHook.accept(strategy);
64:     }
65: 
66:     @Override
67:     public IC4PlayerBuilder changeName(final String newName) {
68:         this.name = Optional.of(newName);
69:         return this;
70:     }
71: 
72:     @Override
73:     public IC4Player build() throws GameException {
74:         return new C4Player(this, this.token, this.name.orElseThrow());
75:     }
76: 
77:     @Override
78:     public int getToken() {
79:         return this.token;
80:     }
81: }