Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package pl.mperor.lab.java.design.pattern.structural.composite;

public interface Ability {

String name();

int value();

static Ability of(String name, int value) {
return new SimpleAbility(name, value);
}

static Ability of(String name, Ability... abilities) {
return new ComplexAbility(name, abilities);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package pl.mperor.lab.java.design.pattern.structural.composite;

import java.util.stream.Collectors;

public class AbilityUtils {

private AbilityUtils() {
}

public static void printAbilityTree(Ability root) {
System.out.println(printAbilityTree(root, 0));
}

private static String printAbilityTree(Ability ability, int level) {
var nested = "";
if (ability instanceof ComplexAbility ca) {
nested = ca.abilities().stream()
.map(a -> printAbilityTree(a, level + 1))
.collect(Collectors.joining());
}

return "%s%s (%d)%n%s".formatted(" ".repeat(level), ability.name(), ability.value(), nested);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package pl.mperor.lab.java.design.pattern.structural.composite;

import java.util.Arrays;
import java.util.List;

public record ComplexAbility(String name, List<Ability> abilities) implements Ability {

public ComplexAbility(String name, Ability... abilities) {
this(name, Arrays.asList(abilities));
}

@Override
public int value() {
return (int) abilities.stream()
.mapToInt(Ability::value)
.average()
.orElse(0);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package pl.mperor.lab.java.design.pattern.structural.composite;

public record SimpleAbility(String name, int value) implements Ability {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package pl.mperor.lab.java.design.pattern.structural.composite;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class AbilityTreeCompositeTest {

@Test
public void testCreateAbilityTree() {
var physicalHealth = Ability.of("Physical Health",
Ability.of("Fitness",
Ability.of("Jogging", 20),
Ability.of("Stretching", 40),
Ability.of("Swimming", 60)
),
Ability.of("Sleep", 50),
Ability.of("Nutrition", 30)
);
Assertions.assertEquals(40, physicalHealth.value());

var mentalHealth = Ability.of("Mental Health",
Ability.of("Stress Management", 50)
);
Assertions.assertEquals(50, mentalHealth.value());

var lifeAndHealth = Ability.of("Life and Health",
physicalHealth,
mentalHealth,
Ability.of("Social Skills", 30)
);
Assertions.assertEquals(40, lifeAndHealth.value());

AbilityUtils.printAbilityTree(lifeAndHealth);
}

}
Loading