조합 모드 예

2985 단어

추상류

/**
 * @see  , ,  
 * @author Thornhill
 *
 */
public abstract class File {
    protected String name;

    public void showSelf(int i) {
    //  
        while (i > 0) {
            System.out.print("  ");
            i--;
        }
    }

    public void add(File f) {
        System.out.println(" ");
    }

    public void remove(File f) {
        System.out.println(" ");
    }

    public List getChild() {
        System.out.println(" ");
        return null;
    }
}

잎류 Image

/**
 * @see  , , , , 。
 * @author Thornhill
 *
 */
public class Image extends File {
    public Image(String name) {
        this.name = name;
    }

    @Override
    public void showSelf(int i) {
        super.showSelf(i);
        System.out.println(" :" + name);

    }

}

잎류 Txt

/**
 * @see  , , , , 。
 * @author Thornhill
 *
 */
public class Txt extends File {
    public Txt(String name) {
        this.name = name;
    }

    @Override
    public void showSelf(int i) {
        super.showSelf(i);
        System.out.println(" :" + name);
    }

}

분기 클래스 폴더

/**
 * @see  , , ,  
 * @author Thornhill
 *
 */
public class Folder extends File {
    private List list = new ArrayList<>();

    public Folder(String name) {
        this.name = name;
    }

    @Override
    public void showSelf(int i) {
        super.showSelf(i);
        System.out.println(" :" + name);
        for (File file : list) {
            file.showSelf(i + 1);
        }
    }

    @Override
    public void add(File f) {
        list.add(f);
    }

    @Override
    public void remove(File f) {
        list.remove(f);
    }

    @Override
    public List getChild() {
        return list;
    }

}

테스트 작성

public class CompositePatternDemo {

    public static void main(String[] args) {
        //  Linux 
        File root = new Folder("root");
        File users = new Folder("user");
        File bin = new Folder("bin");
        //  user 
        File user1 = new Folder("user1");
        File user2 = new Folder("user2");
        //  
        File image1 = new Image("image1");
        File image2 = new Image("image2");
        //  
        File txt1 = new Txt("txt1");
        File txt2 = new Txt("txt2");

        root.add(users);
        root.add(bin);

        users.add(user1);
        users.add(user2);

        bin.add(txt1);

        user1.add(image1);
        user1.add(txt2);

        user2.add(image2);

        root.showSelf(0);
    }

}

출력 확인

 :root
     :user
         :user1
             :image1
             :txt2
         :user2
             :image2
     :bin
         :txt1

좋은 웹페이지 즐겨찾기