jeudi 29 octobre 2015

Java Binary Trees/Visitor Pattern

So I can really get this I was wondering if anyone could help me out, the object of this program is to use the visitor pattern to generate a list of strings from the name of people in a given binary tree, if not really sure how to go about using an append function to do so. How would I append the person with its parents?

import tester.Tester;

//Representation for an ancestor tree
interface IAT {
    <R> R accept(IATVisitor<R> visitor);

    //Append two lists
    IList<String> append(IList<String> l);
}
//-------------------------------------------------------------------------------------------------
//Unknown person
class Unknown implements IAT {
    Unknown() {
    }
    public <R> R accept(IATVisitor<R> visitor) {
        return visitor.visitUnknown(this);
    }
    //append two an unknown
    public IList<String> append(IList<String> l) {
        return l;
    }

}    
//-------------------------------------------------------------------------------------------------
//Representation for a person
class Person implements IAT {
    String name;
    int yob;
    boolean isMale;
    IAT mom;
    IAT dad;
    //Constructor
    Person(String name, int yob, boolean isMale, IAT mom, IAT dad) {
        this.name = name;
        this.yob = yob;
        this.isMale = isMale;
        this.mom = mom;
        this.dad = dad;
    }
    public <R> R accept(IATVisitor<R> visitor) {
        return visitor.visitPerson(this);
    }
    //append parent and children of tree
    public IList<String> append(IList<String> l) {
        //
    }

}
//-------------------------------------------------------------------------------------------------
interface IATVisitor<R> {
    R visitUnknown(Unknown u);
    R visitPerson(Person p);
}
//-------------------------------------------------------------------------------------------------
//IAT Visitor that returns a list of the names of all people
class IATVisitGetNames implements IATVisitor<IList<String>> {
    public IList<String> visitUnknown(Unknown u) {
        return new MT<String>();
    }
    public IList<String> visitPerson(Person p) {
        return new Cons<String>(p.name, new MT<String>());
    }
}

//Examples
class ExamplesIATV {
    //persons
    Unknown a = new Unknown();
    Person ralph = new Person("Ralph", 1995, true, a, a);
    Person kevin = new Person("Kevin", 1994, true, a , a);
    Person julia = new Person("Julia", 1991, false, ralph, a);
    Person lily = new Person("Lily", 1990, false, kevin, julia);
    Person who = new Person("?", 1738, false, lily, a);

    //Visitor
    IATVisitor<IList<String>> byName = new IATVisitGetNames(); 


    //test Vistior
    boolean testGetNames(Tester t) {
        return 
                t.checkExpect(who.accept(byName), new MT<String>());
    }
}

Aucun commentaire:

Enregistrer un commentaire