Last active
October 19, 2023 09:30
-
-
Save adibfara/d6272f976f0188d4c83ffd1f1f5a6330 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Item { | |
void printStructure(); | |
int weight(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public record Box(int weight) implements Item { | |
@Override | |
public int weight() { | |
return weight; | |
} | |
@Override | |
public void printStructure() { | |
System.out.print("*Box"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public record Container(Item[] items) implements Item { | |
@Override | |
public int weight() { | |
var itemsWeight = Arrays.stream(items).mapToInt(Item::weight).sum(); | |
return 2 + itemsWeight; | |
} | |
@Override | |
public void printStructure() { | |
System.out.print(" Container["); | |
for (Item item : items) { | |
item.printStructure(); | |
} | |
System.out.print("]"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) { | |
var ensemble = new Container( | |
new Item[]{ | |
new Box(2), | |
new Container(new Item[]{ | |
new Box(3), | |
new Box(4)} | |
)}); | |
ensemble.printStructure(); | |
System.out.println(); | |
System.out.println("Total weight is: " + ensemble.weight()); | |
} | |
// Container[*Box Container[*Box*Box]] | |
//Total weight is: 13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment