// The program tests for the total weight of apples in a basket Basket { // NOTE: the printing of apples wasn't implemented in the Demeter/C++ // program which I found out after doing it in my program. // So, basically I just did some extra work. // All apples inside the nested baskets have to be printed // So, first it traverses to thing and then from thing to basket and // then to apple (@ void find_Thing() { TraverseThingVisitor ttv = new TraverseThingVisitor(); this.all_things(ttv); } @) traversal all_things(TraverseThingVisitor ttv) { to Thing; } (@ void all_apples() { PrintingVisitor pv = new PrintingVisitor(); this.print_allapples(pv); } @) traversal print_allapples(PrintingVisitor pv) { to Apple; } traversal sum_Apples(SummingVisitor sum) { to Apple; } } Thing { // Finds the nested baskets in Thing (@ void find_nested_basket() { TraverseBasketVisitor tbv = new TraverseBasketVisitor(); this.all_baskets(tbv); } @) traversal all_baskets(TraverseBasketVisitor tbv) { to Basket; } } Apple { // Returns the weight of the apple (@ Integer get_apple_weight() { GetWeightVisitor gwv = new GetWeightVisitor(); this.find_Weight(gwv); return(gwv.get_val()); } @) traversal find_Weight(GetWeightVisitor gwv) { to Weight; } } // Used to find the nested baskets in a thing TraverseThingVisitor { before Thing (@ host.find_nested_basket(); @) } // Used to find all apples in a basket TraverseBasketVisitor { before Basket (@ host.all_apples(); @) } // Used to get the weight of the apple. It was implemented to get around // breaking the Law of Demeter GetWeightVisitor { before Weight (@ this.set_val(host.get_v()); @) } // I have commented out the print statement because I wasn't supposed to // do this in the first place. PrintingVisitor { // before Apple (@ System.out.println("apple"); @) } // Calculates the total weight of apples in a basket SummingVisitor { before Apple (@ total = new Integer(total.intValue() + host.get_apple_weight().intValue()); @) } Main { (@ static public void main(String args[]) throws Exception { Basket basket = Basket.parse(System.in); SummingVisitor sum = SummingVisitor.parse("0"); basket.find_Thing(); basket.sum_Apples(sum); int total_weight = sum.get_total().intValue(); // For the given program input, the sum of the weights of // apples is 10 System.out.println("Total Weight of Apples = " + total_weight); System.out.println("Expected = 10"); int expected = 10; if (expected == total_weight) { System.out.println("SUCCESS"); } else { System.out.println("FAILURE"); } } @) }