본문 바로가기

객체지향

[디자인패턴] Composite pattern

반응형

https://it-mesung.tistory.com/176

 

[디자인 패턴] 컴포지트 패턴

컴포지트 패턴을 통해 트리 구조를 구현할 수 있다. 컴포지트란 하나 이상의 유사한 객체를 구성으로 설계된 객체로 모두 유사한 기능을 나타낸다. 이를 통해 객체 그룹을 조작하는 것처럼 단일

it-mesung.tistory.com

https://www.youtube.com/watch?time_continue=294&v=78uNgDSHw-k&feature=emb_title 

 

컴포지트 패턴(Composite pattern)이란 객체들의 관계를 트리 구조로 구성하여 부분-전체 계층을 표현하는 패턴으로, 사용자가 단일 객체와 복합 객체 모두 동일하게 다루도록 한다.

컴포지트 패턴은 클라이언트가 복합 객체나 단일 객체를 동일하게 취급하는 것을 목적으로 한다. 여기서 컴포지트의 의도는 트리 구조로 작성하여 전체-부분 관계를 표현하는 것이다.

 

컴포지트 패턴은 언제 사용하는가?

복합 객체와 단일 객체의 처리 방법이 다르지 않을 경우, 전체-부분 관계로 정의할 수 있다.

 

public class Main {
    public static void main(String[] args) {
        Folder
                root = new Folder("root"),
                home = new Folder("home"),
                gram = new Folder("gram"),
                music = new Folder("music"),
                picture = new Folder("picture"),
                doc = new Folder("doc"),
                usr = new Folder("usr");

        File
                track1 = new File("track1"),
                track2 = new File("track2"),
                pic1 = new File("pic1"),
                doc1 = new File("doc1"),
                java = new File("java");

        root.addComponent(home);
           home.addComponent(gram);
               gram.addComponent(music);
                    music.addComponent(track1);
                    music.addComponent(track2);
              gram.addComponent(picture);
                   picture.addComponent(pic1);
              gram.addComponent(doc);
                 doc.addComponent(doc1);
        root.addComponent(usr);
                usr.addComponent(java);

                show(root);
    }
    private static void show(Component component){
        System.out.println(component.getClass().getName()+"|"+component.getName());
        if(component instanceof Folder){
            for(Component c:((Folder)component).getChildren()){
                show(c);
            }
        }
    }
}

/구현을 공유해야할 필요가 있으면 추상클래스, 공유할 필요가 없으면 인터페이스

abstract public class Component {
    private String name;
    public Component(String name){
        this.name= name;
    }
    public String getName(){
        return name;
    }
    public void setName(String str){
        this.name=str;
    }
}
public class File  extends Component{
    private Object data;

    public File(String name) {
        super(name);
    }

    public Object getData(){
        return data;
    }
    public void setData(Object data){
        this.data=data;
    }
}
import java.util.ArrayList;
import java.util.List;

public class Folder extends Component{
    List<Component> children= new ArrayList<>();

    public Folder(String name) {
        super(name);
    }

    public boolean addComponent(Component component){
        return  children.add(component);
    }
    public boolean removeComponent(Component component){
        return  children.remove(component);
    }
    public List<Component> getChildren(){
        return children;
    }

}

Folder|root
Folder|home
Folder|gram
Folder|music
File|track1
File|track2
Folder|picture
File|pic1
Folder|doc
File|doc1
Folder|usr
File|java

 

장점

객체들이 모두 같은 타입으로 취급되기 때문에 새로운 클래스 추가가 용이하다.

단일 객체, 집합 객체 구분하지 않고 코드 작성이 가능하다.

 

단점

설계를 일반화 시켜 객체간의 구분, 제약이 힘들다.

 

언제 사용하나?

객체들 간에 계급 및 계층구조가 있고 이를 표현해야 할 때

클라이언트가 단일 객체와 집합객체를 구분하지 않고 동일한 형태로 사용하고자 할 때

 

복합객체는 한 객체가 다른 객체를 포함하는 객체를 말한다.

출처: https://develop-im.tistory.com/68 [IsBerry]

반응형