[JAVA] Introduction to Design Patterns (Composite)

This article summarizes Composite. According to wikipedia, "it can represent recursive data structures with tree structures, such as directories and files." Reference: Composite pattern

If you're in an object-thinking language, you'll probably see a lot of things like arrays, stacks, lists, hashes, and other collections that are packed with objects and processed in order. In the Composite pattern, the difference between individual objects is ignored even if the objects have a tree-like structure (a structure in which objects that hold child elements and objects that do not have child elements are mixed), such as "single-many". And apply the same process.

Sketch of components

Composite node
 |-Leaf node
 |-Leaf node
 |-Leaf node

** Main characters **

no name role
1 component One unit of node such as composite and leaf is called like this. Interface to implement on node
2 Composite node Object that holds child elements
3 Leaf node Objects that have no child elements

** Implement the pattern ** By combining nodes like a hierarchy, the intricate configuration is expressed as follows. Consider the fictitious dining room menu table.

Dining room menu

 |  |-Set meal A ¥ 1,000
 |  |-Set meal B ¥ 1,200
 |  |-Ramen ¥ 900
 |  |-Udon ¥ 800
    |-Coke ¥ 250
    |-Tea ¥ 300


public abstract class MenuComponent {
    public void add(MenuComponent mc) {
        throw new UnsupportedOperationException();
    public void remove(MenuComponent mc) {
        throw new UnsupportedOperationException();
    public MenuComponent getChild(Integer i) {
        throw new UnsupportedOperationException();

    abstract public String getName();
    abstract public String getDescription();
    abstract public void print();


import java.util.ArrayList;
import java.util.Iterator;

public class Menu extends MenuComponent {
    ArrayList<MenuComponent> mcs = new ArrayList<>();
    String name;
    String description;

    public Menu(String name, String description) {
        this.name = name;
        this.description = description;
    public void add(MenuComponent mc) { mcs.add(mc); }
    public void remove(MenuComponent mc) { mcs.remove(mc); }
    public MenuComponent getChild(Integer i) { return mcs.get(i); }
    public String getName() { return name; }
    public String getDescription() { return description; }
    public void print() {
        System.out.print("\n" + getName());
        System.out.println("," + getDescription());
        Iterator iterator = mcs.iterator();
        while(iterator.hasNext()) {
            MenuComponent mc = (MenuComponent) iterator.next();


public class MenuItem extends MenuComponent {
    public String name;
    public String description;
    public Boolean coffee;
    public Integer price;

    public MenuItem(String name, String description, Boolean coffee, Integer price) {
        this.name = name;
        this.description = description;
        this.coffee = coffee;
        this.price = price;
    public String getName() { return name; }
    public String getDescription() { return description; }
    public Integer getPrice() { return price; }
    public Boolean isCoffee() { return coffee; }
    public void print() {
        System.out.print(" " + getName());
        if (isCoffee()) System.out.print("(With coffee)");
        System.out.println("," + getPrice());
        System.out.println(" -- " + getDescription());


public class Main {
    public static void main(String args[]) {
         MenuComponent rice = new Menu("rice", "Set meal menu");
         MenuComponent noodles = new Menu("noodles", "noodles類メニュー");
         MenuComponent drink = new Menu("drink", "drinkメニュー");
         MenuComponent all = new Menu("menu", "Click here today");
         rice.add(new MenuItem("Set meal A", "Advantageous set meal set A", true, 1000));
         rice.add(new MenuItem("Set meal B", "Advantageous set meal set B", true, 1200));
         noodles.add(new MenuItem("ramen", "自家製ramen", false, 900));
         noodles.add(new MenuItem("Udon", "本格Udon", false, 800));
         drink.add(new MenuItem("Cola", "Red package", false, 250));
         drink.add(new MenuItem("tea", "どこにでもあるtea", false, 300));


$java Main
menu,Click here today
rice,Set meal menu
Set meal A(With coffee),1000
 --Advantageous set meal set A
Set meal B(With coffee),1200
 --Advantageous set meal set B

 --Homemade ramen
 --Authentic udon

 --Red package
 --Tea everywhere

The pattern is applied by print () in Menu.java. As for the structure of the object, the Menu class defines the category, and the MenuItem class manages the menu details (menu, details, price, coffee presence / absence). Menu object and MenuItem object are saved in List of Menu class, and when print () outputs data, output processing is executed for each regardless of the existence and number of Menu object and MenuItem object.

Reference: [Head First Design Patterns-Design Patterns to Remember with Your Head and Body] (https://www.amazon.co.jp/Head-First%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3-%E2%80%95%E9%A0%AD%E3%81%A8%E3%81%8B%E3%82%89%E3%81%A0%E3%81%A7%E8%A6%9A%E3%81%88%E3%82%8B%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%E3%81%AE%E5%9F%BA%E6%9C%AC-Eric-Freeman/dp/4873112494)

Recommended Posts

Introduction to Design Patterns (Composite)
Introduction to design patterns (introduction)
Introduction to design patterns (Flyweight)
Introduction to design patterns Prototype
Introduction to Design Patterns (Iterator)
Introduction to Design Patterns (Strategy)
Introduction to Design Patterns (Factory Method)
Introduction to Design Patterns (Abstract Factory)
Important design patterns to improve maintainability
Introduction to Ruby 2
Various design patterns
Design pattern ~ Composite ~
Java Design Patterns
Introduction to web3j
Introduction to Micronaut 1 ~ Introduction ~
[Java] Introduction to Java
Introduction to migration
Introduction to java
Introduction to Doma
Introduction to JAR files
Introduction to bit operation
Introduction to Ratpack (6) --Promise
Introduction to Ratpack (9) --Thymeleaf
Introduction to PlayFramework 2.7 ① Overview
Introduction to Android Layout
Introduction to Practical Programming
Introduction to javadoc command
Introduction to jar command
Introduction to Ratpack (2)-Architecture
Introduction to lambda expression
Introduction to java command
Introduction to RSpec 2. RSpec setup
Introduction to Keycloak development
Study GoF design patterns
Introduction to javac command
I read Hiroshi Yuki "Introduction to Design Patterns Learned in Java Language" (SB Creative)
Introduction to RSpec 5. Controller specs
Introduction to RSpec 6. System specifications
Introduction to Android application development
Introduction to RSpec 3. Model specs
Introduction to Ratpack (5) --Json & Registry
Introduction to Metabase ~ Environment Construction ~
Introduction to Ratpack (7) --Guice & Spring
(Dot installation) Introduction to Java8_Impression
Introduction to Micronaut 2 ~ Unit test ~
Introduction to JUnit (study memo)
Introduction to Spring Boot ① ~ DI ~
[Java] Introduction to lambda expressions
Introduction to Spring Boot ② ~ AOP ~
Introduction to Apache Beam (2) ~ ParDo ~
[Ruby] Introduction to Ruby Error statement
Introduction to EHRbase 2-REST API
GitHub Actions Introduction to self-made actions
[Java] Introduction to Stream API
Introduction to Spring Boot Part 1
Introduction to Ratpack (1) --What is Ratpack?
XVim2 introduction memo to Xcode12.3
Why design patterns are needed
[Java] Summary of design patterns
Introduction to RSpec-Everyday Rails Summary-
[Introduction to rock-paper-scissors games] Java