본문 바로가기
java

[Java11] Composite Pattern 컴포지트 패턴

by moonsiri 2023. 9. 21.
728x90
반응형

Composite Pattern

객체들의 관계를 트리 구조로 구성하여 부분-전체 계층을 표현하는 패턴

사용자가 단일 객체와 복합 객체 모두 동일하게 다루도록 하는 패턴

  • Base Component
    • 클라이언트가 composition내의 오브젝트들을 다루기 위해 제공되는 인터페이스
    • 인터페이스 또는 추상 클래스로 정의되며 모든 오브젝트들에게 공통되는 메서드를 정의해야 함
  • Leaf
    • composition 내 오브젝트들의 행동을 정의
    • 베이스 컴포넌트를 구현
    • 다른 컴포넌트에 대해 참조를 가지면 안됨
  • Composite
    • Leaf 객체들로 이루어져 있으며 베이스 컴포넌트 내 명령들을 구현
    • 복수개의 Leaf, 복수개의 Composite 객체를 부분으로 가질 수 있음

 

 

 

1. Base Component

Leaf와 Composite의 공통되는 메서드들을 정의해야 함

public interface Shape {
    public void draw(String fillColor);
}

 

 

2. Leaf Objects

복합체에 포함되는 요소로, Base Component를 구현해야 함

public class Triangle implements Shape {
 
    @Override
    public void draw(String fillColor) {
        System.out.println("Drawing Triangle with color "+fillColor);
    }
}
public class Circle implements Shape {
 
    @Override
    public void draw(String fillColor) {
        System.out.println("Drawing Circle with color "+fillColor);
    }
}

 

 

3. Composite Objects

Leaf 객체들을 포함하고 있으며, Base Componet를 구현할 뿐만 아니라 Leaf 그룹에 대해 add와 remove를 할 수 있는 메서드들을 클라이언트에 제공

public class Drawing implements Shape {
 
    //collection of Shapes
    private List<Shape> shapes = new ArrayList<Shape>();
	
    @Override
    public void draw(String fillColor) {
        for(Shape sh : shapes) {
            sh.draw(fillColor);
        }
    }
	
    //adding shape to drawing
    public void add(Shape s) {
        this.shapes.add(s);
    }
	
    //removing shape from drawing
    public void remove(Shape s) {
        shapes.remove(s);
    }
	
    //removing all the shapes
    public void clear() {
        System.out.println("Clearing all the shapes from drawing");
        this.shapes.clear();
    }
}

여기서 중요한 것은 Composite Object 또한 Base Component를 구현해야 한다

그렇게 해야만 클라이언트가 Composite 객체에 대해서 다른 Leaf들과 동일하게 취급될 수 있다.

 

 

테스트

public class TestCompositePattern {
 
    public static void main(String[] args) {
        Shape tri = new Triangle();
        Shape tri1 = new Triangle();
        Shape cir = new Circle();
		
        Drawing drawing = new Drawing();
        drawing.add(tri1);
        drawing.add(tri1);
        drawing.add(cir);
		
        drawing.draw("Red");
		
        List<Shape> shapes = new ArrayList<>();
        shapes.add(drawing);
        shapes.add(new Triangle());
        shapes.add(new Circle());
        
        for(Shape shape : shapes) {
            shape.draw("Green");
        }
    }
}

 

결과

Drawing Triangle with color Red
Drawing Triangle with color Red
Drawing Circle with color Red
Drawing Triangle with color Green
Drawing Triangle with color Green
Drawing Circle with color Green
Drawing Triangle with color Green
Drawing Circle with color Green

위 코드를 보시면 drawing 객체를 통해 Triangle, Circle 등의 Leaf 객체들을 Group으로 묶어서 한 번에 동작을 수행할 수 있다. 나아가 drawing 객체 또한 다른 도형들과 마찬가지로 Shape 인터페이스를 구현하고 있기 때문에 변수 shapes에서 살펴보는 것과 같이 drawing이 다른 도형들과 함께 취급될 수 있다.

 

 

[Reference]

https://readystory.tistory.com/131

728x90
반응형

댓글