public enum Action {
HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD("found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE("", "");
private String title; private String description;
Action(String title, String description) { this.title = title; this.description = description; }
public String getDescription() { return description; }
public String toString() { return title; } }
public interface Party {
void addMember(PartyMember member);
void act(PartyMember actor, Action action);
}
public interface PartyMember {
void joinedParty(Party party);
void partyAction(Action action);
void act(Action action); }
public class PartyImpl implements Party {
private final List<PartyMember> members;
public PartyImpl() { members = new ArrayList<>(); }
@Override public void act(PartyMember actor, Action action) { for (PartyMember member : members) { if (!member.equals(actor)) { member.partyAction(action); } } }
@Override public void addMember(PartyMember member) { members.add(member); member.joinedParty(this); } }
public abstract class PartyMemberBase implements PartyMember {
private static final Logger LOGGER = LoggerFactory.getLogger(PartyMemberBase.class);
protected Party party;
@Override public void joinedParty(Party party) { LOGGER.info("{} joins the party", this); this.party = party; }
@Override public void partyAction(Action action) { LOGGER.info("{} {}", this, action.getDescription()); }
@Override public void act(Action action) { if (party != null) { LOGGER.info("{} {}", this, action); party.act(this, action); } }
@Override public abstract String toString();
}
public class Hobbit extends PartyMemberBase {
@Override public String toString() { return "Hobbit"; }
}
public class Hunter extends PartyMemberBase {
@Override public String toString() { return "Hunter"; } }
public class Rogue extends PartyMemberBase {
@Override public String toString() { return "Rogue"; }
}
public class Wizard extends PartyMemberBase {
@Override public String toString() { return "Wizard"; }
}
public class App {
public static void main(String[] args) {
Party party = new PartyImpl(); Hobbit hobbit = new Hobbit(); Wizard wizard = new Wizard(); Rogue rogue = new Rogue(); Hunter hunter = new Hunter();
party.addMember(hobbit); party.addMember(wizard); party.addMember(rogue); party.addMember(hunter);
hobbit.act(Action.ENEMY); wizard.act(Action.TALE); rogue.act(Action.GOLD); hunter.act(Action.HUNT); } }
|