// Bryan Chadwick // Visit.java // Container problem using DJ and Visitors import edu.neu.ccs.demeter.dj.*; import java.util.Stack; public class Visit{ public static void main(String[] args) { ClassGraph cg = new ClassGraph(true,false); Container con; con = new Container(18,new Item[]{new Element(4), new Container(8,new Item[]{new Element(4), new Element(3)}), new Element(1), new Container(5,new Item[]{new Element(6), new Element(1)})}); Strategy s = new Strategy("from Container via Item to Element"); TraversalGraph tg = new TraversalGraph(s, cg); ViolationVisitor vv = new ViolationVisitor(); tg.traverse(con,vv); int i = ((Integer)(vv.getReturnValue())).intValue(); System.out.println("Violations : "+i); } } interface Item{} // Visitor that just collects the Weight class WeightVisitor extends Visitor{ int weight = 0; public void before(Element e){ weight += e.weight; } public Object getReturnValue(){ return new Integer(weight); } } // Visitor that collects Weight, and checks for capacity violations class ViolationVisitor extends Visitor{ int weight = 0; int violations = 0; Stack stack = new Stack();// stack = new Stack(); public void before(Element e){ weight += e.weight; } public void before(Container c){ stack.push(new Integer(weight)); } public void after(Container c){ if((weight - ((Integer)stack.pop()).intValue()) > c.capacity) violations++; } public Object getReturnValue(){ return new Integer(violations); } } // Represents something of Weight class Element implements Item{ public int weight; public Element(int w){ weight = w;} } // Represents a Weightless container, with a capacity // meening the only things with weight are Elements // and Containers that contain Elements...etc class Container implements Item{ public Item [] items; public int capacity; public Container(int c, Item[] i){items = i; capacity = c;} }