In: Computer Science
a Composite class representing arithmetic expression.
Participants:
Q. Create a code implementing a pattern, Implementing Composite implies multiple class. By my estimate, at least 3. In minimal Composite implementation, classes have two methods (or a constructor and 1 method). extensive coding is not required. (using Java)
public interface Arithmetic {
double compute();
default void appendChild(Arithmetic arithmetic) {}
default void removeChild(Arithmetic arithmetic) {}
}
Next, we have Leaf nodes, which each represent a singular operation.
public class Addition implements Arithmetic {
private final double x;
private final double y;
public Addition(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public double compute() {
return x + y;
}
}
public class Subtraction implements Arithmetic {
private final double x;
private final double y;
public Subtraction(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public double compute() {
return x - y;
}
}
And finally, a Composite node, which represents multiple operations.
public class CompositeAddition implements Arithmetic {
private final List<Arithmetic> operations = new ArrayList<>();
public CompositeAddition(Arithmetic... arithmetics) {
operations.addAll(Arrays.asList(arithmetics));
}
@Override
public double compute() {
return operations.stream().mapToDouble(Arithmetic::compute).sum();
}
@Override
public void appendChild(Arithmetic arithmetic) {
operations.add(arithmetic);
}
@Override
public void removeChild(Arithmetic arithmetic) {
operations.remove(arithmetic);
}
}
I leave the remaining arithmetic types as an exercise for the reader. These few classes are sufficient for a demonstration.
public class Main {
public static void main(String... args) {
Arithmetic fivePlusTwo = new Addition(5,2);
Arithmetic fiveMinusTwo = new Subtraction(5,2);
Arithmetic sevenPlusThree = new CompositeAddition(fivePlusTwo, fiveMinusTwo);
System.out.println(sevenPlusThree.compute());
}
}
Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! ===========================================================================