Skip to content

Commit

Permalink
Added Composite pattern for Java
Browse files Browse the repository at this point in the history
  • Loading branch information
akhtyamovpavel committed Mar 20, 2023
1 parent 0021e04 commit f7166fe
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 0 deletions.
6 changes: 6 additions & 0 deletions JavaSource/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@
<mainClass>ru.akhcheck.patterns.bridge.MainBridge</mainClass>
</configuration>
</execution>
<execution>
<id>Composite</id>
<configuration>
<mainClass>ru.akhcheck.patterns.composite.MainComposite</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ru.akhcheck.patterns.composite;

public class Breakfast extends Dish {
@Override
public int GetCalories() {
return super.GetCalories() + 10;
}
}
21 changes: 21 additions & 0 deletions JavaSource/src/main/java/ru/akhcheck/patterns/composite/Dish.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ru.akhcheck.patterns.composite;

import java.util.ArrayList;

public class Dish implements DishComponent{
private ArrayList<DishComponent> components = new ArrayList<>();

public int GetCalories() {
int calories = 0;
for (DishComponent component: components) {
calories += component.GetCalories();
}
return calories;
}

public Dish add(DishComponent component) {
components.add(component);
return this;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package ru.akhcheck.patterns.composite;

public interface DishComponent {
int GetCalories();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ru.akhcheck.patterns.composite;

public class MainComposite {


public static void main(String[] args) {
Dish ration = new Dish().add(
new Breakfast().add(
new Milk()
).add(
new Milk()
)
).add(new Milk());
System.out.println(ration.GetCalories());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package ru.akhcheck.patterns.composite;

public class Milk implements DishComponent {

@Override
public int GetCalories() {
return 100;
}
}

0 comments on commit f7166fe

Please sign in to comment.