Skip to content

Instantly share code, notes, and snippets.

@mitulmanish
Created April 25, 2016 13:34
Show Gist options
  • Save mitulmanish/b078cccfcfb44c2ace183e90f99adcc9 to your computer and use it in GitHub Desktop.
Save mitulmanish/b078cccfcfb44c2ace183e90f99adcc9 to your computer and use it in GitHub Desktop.
Example of Composite Design pattern
package com.company;
import java.util.ArrayList;
interface Shape{
void draw(String fillColor);
}
class Square implements Shape{
@Override
public void draw(String fillColor) {
System.out.print("Filling in the square with " + fillColor);
}
}
class Circle implements Shape{
@Override
public void draw(String fillColor) {
System.out.println("Filling in the circle with " + fillColor);
}
}
class WhiteBoard implements Shape {
private ArrayList<Shape> shapes;
public WhiteBoard(ArrayList<Shape> shapes) {
this.shapes = shapes;
}
@Override
public void draw(String fillColor) {
shapes.forEach((shape) -> {
shape.draw(fillColor);
});
}
}
public class Main {
public static void main(String[] args) {
// write your code here
ArrayList<Shape> shapes = new ArrayList<>();
shapes.add(new Circle());
shapes.add(new Square());
WhiteBoard whiteBoard = new WhiteBoard(shapes);
whiteBoard.draw("Red");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment