/***********************/ // MAIN.JAVA /***********************/ class Main { static public void main(String args[]) throws Exception { Container c1=new Container("Container 1",5); Container c2=new Container("Container 2",1); Container c3=new Container("Container 3",1); Simple apple=new Simple("apple",1); Simple pencil=new Simple("pencil",1); Simple orange=new Simple("orange",1); Simple kiwi=new Simple("kiwi",1); Simple banana= new Simple("banana",1); c3.addItem(kiwi); c2.addItem(c3); c2.addItem(apple); c1.addItem(orange); c1.addItem(pencil); c1.addItem(c2); c1.check(); c1.addItem(banana); c1.check(); } } /***********************/ // ITEM.JAVA /***********************/ abstract class Item { String name; public Item(String n) { name=n; } public abstract int check(); } class Cache.Item { Container container; public void setContainer(Container c) { container=c; } public Container getContainer() { return container; } } /***********************/ // CONTAINER.JAVA /***********************/ import java.util.*; class Container extends Item { Vector contents=new Vector(); int capacity; public Container(String n,int c) { super(n); capacity=c; } public void addItem(Item i) { contents.add(i); // i.setContainer(this); } // This check is OVER-RIDDEN public int check() { Iterator it=contents.iterator(); int total = 0; while(it.hasNext()) { total+=((Item)it.next()).getWeight(); } System.out.println("Container "+name+" weighs "+total); if(total>capacity) { System.out.println("Container "+name+" overloaded"); } return total; } } class Cache.Container { bool cache = false; int cached_weight; private void invalidateCache() { cache = false; getContainer.invalidateCache(); } void afterAddItem() { invalidateCache(); // how to set container on item ? } // With cacheing in place this is the real check public int check() { if (cache) return cached_weight; Iterator it=contents.iterator(); int total = 0; while(it.hasNext()) { total+=((Item)it.next()).check(); cached_weight = total; cache = true; } System.out.println("Container "+name+" weighs "+total); if(total>capacity) { System.out.println("Container "+name+" overloaded"); } return total; } } /***********************/ // SIMPLE.JAVE /***********************/ class Simple extends Item { int weight; public Simple(String n,int w) { super(n); weight=w; } public int check() { System.out.println("Simple object "+name+" weighs "+weight); return weight; } }