11 컴포지트 패턴 (Composite Pattern)

2021. 12. 13. 14:23 JAVA/Design Patterns

컴포지트 패턴 (Composite Pattern)


객체들을 트리 구조로 구성하여 그릇 객체와 내용물 객체를 동일하게 취급할 수 있도록 만들기 위한 패턴입니다.

 

 

Composite Pattern Structure


 Component : Leaf와 Composite의 상위 클래스로써 이들을 동일하게 취급 할 수 있도록 공통 인터페이스 정의

 Composite : 그릇을 나타내는 역할을 하고, 또 다른 그릇을 참조하거나 내용물 객체를 참조 할 수 있음

 Leaf : 내용물 객체로서, 그릇 객체를 포함 할 수 없음

 

 

예제


예제는 디렉토리 구조를 구성하는 예제로 디렉토리는 그릇 객체에 해당되며 파일은 내용물 객체에 해당합니다.

예제의 클래스 다이어그램입니다. Entry 객체는 File과 Directory를 동일 취급 하기 위한 공통 인터페이스를 정의하고 Directory는 그릇으로 또 다른 디렉토리 또는 파일을 포함하고 관리 할 수 있는 메서드를 구현합니다.

 

Entry.class

public abstract class Entry {
    String name;
    public Entry(String name)
    {
        this.name = name;
    }
    
    public abstract void add(Entry entry);
    public abstract void PrintList(String path);
}
 

 

Entry 클래스는 File과 Directory의 상위 클래스로 공통인터페이슬 정의하고, 디렉토리명 또는 파일명을 생성인자로 하는 생성자를 제공합니다. 하위에서는 자식 객체를 추가 할 수 있는 add() 메서드와 디렉토리 경로를 보여주는 PrintList() 메서드를 구현합니다.

 

File.class

 
public class File extends Entry {
    public File(String name)
    {
        super(name);
    }
    public void add(Entry entry){}
    public void PrintList(String path)        
    {
        System.out.println(path +"/" +this.name);

    }
}

 

File은 내용물 객체로 안에 또 다른 객체를 포함 할 수 없습니다. add() 구현을 비워두고 구현을 하였습니다.

 

Directory.class

public class Directory extends Entry {
    
    ArrayList<Entry> directory = new ArrayList();    //자식 객체를 담기 위한 ArrayList
    
    public Directory(String name)
    {
        super(name);
    }
    public void add(Entry entry)                    //자식 객체 추가
    {
        directory.add(entry);
    }
    public void PrintList(String path)        //디렉토리 목록을 보여줍니다.
    {
        path += "/" +this.name;
        System.out.println(path);
        for(int i=0; i<directory.size();i++)
        {
            directory.get(i).PrintList(path );
        }
    }
}
 

그릇 객체에 해당하는 Directory 입니다. 하위에 존재하는 자식 객체들 (Directory,file)을 관리하기 위한 ArrayList가 존재하며 add()메서드를 통해 객체를 추가합니다.

PrintList에서는 ArrayList에 존재하는 자식 객체들의 대한 PrintList() 메서드를 호출시킵니다. (재귀적인 구조)

 

Mai.class

public class Main {

    public static void main(String argsp[])
    {    
        Directory root = new Directory("root");
        Directory bin = new Directory("bin");
        Directory Lkt = new Directory("Lkt");
        File file1 = new File("file1");
        File file2 = new File("file2");
        File file3 = new File("file3");
        File file4 = new File("file3");
        
        root.add(file1);    //루트 디렉토리에 file1 포함
        bin.add(file2);        //bin 디렉토리에 file2 포함
        bin.add(file3);        //bin 디렉토리에 file3 포함
        Lkt.add(file4);        //Lkt 디렉토리에 file4 포함
        root.add(Lkt);        //root 디렉토리에 Lkt 디렉토리 포함
        root.add(bin);        //root 디렉토리에 bin 디렉토리 포함
        
        root.PrintList("");
    }
}
 

실제 메인에서 디렉토리 구조를 구성하고 디렉토리 목록을 보여줍니다.

 

 

출처 : https://lktprogrammer.tistory.com/49?category=672216