Dog
Dog

Reputation: 29

java Composite design pattern(Directory &File)

The outputs below are different. I don't know what's wrong and I have tried to correct many times. There has File and Folder two java files.And for the format, for a listed folder,there must be a "/" at the end and for each folder/file, the path must be the absolute path.

The output must be

dir1/
dir1/f1/
dir1/dir2/
dir1/dir2/f3/
dir1/dir2/f4/
dir1/dir2/dir3/
dir1/dir2/dir3/f5/
dir1/f2/

However,my output is

dir1/
dir1/f1/
dir1/dir2/
dir2/f3/
dir2/f4/
dir2/dir3/
dir3/f5/
dir1/f2/

Here is my code.

public class File implements Composite {
    public String name;
    //private ArrayList<File>a=new ArrayList<File>();


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


    public void list() {

        System.out.print(name+"/");
       System.out.println();
    }
}  

Folder.java

import java.util.ArrayList;

public class Folder implements Composite{
    public String name;
    public ArrayList b = new ArrayList();

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

    public void add(Object o) 
    {

        b.add(o);
    }

    public void list(){
           int e=b.indexOf(name)+1;
           System.out.println(name+"/");
           Composite r=(Composite) b.get(e); 
           for(int i=0;i<b.size();i++) {

               System.out.print(name+"/");



               Composite a=(Composite)b.get(i);

               a.list();
           }

    }

    public String getName(){
        return name;
    }
}

Upvotes: 0

Views: 1772

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328584

In your code, you need to track the parent folder of each Folder.

So the constructor needs to be Folder(Folder parent, String name). The root (topmost) folder has null as parent.

When you print the name, you need to ask the current folder for it's path. The code for this method would be:

 public String getPath() {
     if(null == parent) return name;

     return parent.getPath() + "/" + name;
 }

Upvotes: 2

Related Questions