본문 바로가기
프로그래밍/디자인 패턴(프로그래밍)

[Design Pattern]Composite Pattern이란?

by 그래도동 2019. 1. 18.
728x90
반응형

Composite Pattern이란?

 객체들을 트리 구조로 구성하여 단일 객체와 복합객체를 동일하게 제어 가능하도록 하는 패턴



Composite Pattern 3요소


component : leaf와 composite의 상위클래스로써 이들을 동일하게 취급하게할 interface. composition(구성자)을 위한 인터페이스로 구성. client class는 이 인터페이스를 사용하여 작업한다. interface 또는 abstract class 그리고 모든 클래스를 위한 약간의 공통 메소드 역시 포함한다.

leaf : component를 구현하는 클래스 요소로 이 클래스들을 쌓아올려 하나의 구성물을 만든다. 

composite : 다수의 leaf 클래스를 제어하는 클래스로 component를 이용해 공통 작업을 할 수 있는 클래스



예제


component

1
2
3
4
public interface Car 
{
    public void Painting(String color);
}
cs

leaf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Jeep implements Car 
{
    @Override
    public void Painting(String color) 
    {
        System.out.print("Jeep color: " + color);
    }
}
 
public class Bmw implements Car 
{
    @Override
    public void Painting(String color) 
    {
        System.out.print("Bmw color: " + color);
    }
}
 
public class K5 implements Car 
{
    @Override
    public void Painting(String color) 
    {
        System.out.print("K5 color: " + color);
    }
}
cs


composite

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class PlayPainting implements Car 
{
    private List<Car> cars = new ArrayList<Car>();
 
    @Override
    public void draw(String color) 
    {
        for (Car c : cars) 
        {
            c.draw(color);
        }
    }
 
    public void add (Cars car) 
    {
        this.cars.add(car);
    }
 
    public void remove (Cars car) 
    {
        this.cars.remove(s);
    }
 
    public void clear () 
    {
        this.cars.clear();
    }
}
cs


main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class PaintingMain 
{
    public static void main(String[] args) 
    {
        Car bmw = new Bmw();
        Car jeep = new Jeep();
        Car k5 = new K5();
 
        PlayPainting carPainting = new PlayPainting();
        carPainting.add(bmw);
        carPainting.add(jeep);
        carPainting.add(k5);
        carPainting.Painting("red");
 
        carPainting.clear();
 
        carPainting.add(bmw);
        carPainting.add(jeep);
        carPainting.Painting("blue");
    }
}
cs


단일 객체처럼 행동하는 다수의 객체(인터페이스가 같거나, 비슷한 객체)가 있는 경우 적용가능하다.


Reference

 https://blog.seotory.com/post/2017/09/java-composite-pattern

728x90
반응형

댓글