CSC223, Class 4: Polymorphic Candy, Continued Admin: * Remind: Email me when you miss class, but please don't miss class. * Homework assignment coming at the end of class. Overview: * Review polymorphic candy example * Solution one: Modify CandyMachine interface. * Solution two: Use Java introspection. * Solution three: Use the "Abstract Factory" design pattern * Improving solution three with "anonymous inner classes" Summarize polymorphic candy machine problem * The problem: * We want to build many candy machines of the same type Solution one: Rewrite the problem * Add a "refill()" method to the CandyMachine interface. * Positives * Continues to use a nice interface. * Pushes the problem "up" a level. * Models the real world well. * Relatively easy * Negatives * May not be "efficient" (might repeat similar code) (LZ-B agrees) * Changing a published interface is EVIL * Morals: * Take care in designing interfaces. * Do not change interfaces lightly. Solution two: Use great knowledge of Java (Introspection) * Get the class of the candy machine. * Use that to make a new one * Positives: * Doesn't change the interface. * Straightforward and logical: You need to know the class, so you ask it for the class. * Negatives: * Harder to code. * Fails to work for base classes that lack zeroary constructors. * Will it work for DoubleMachine? * Theoretical: DoubleMachines have no zeroary constructor, so it is likely that the getConstructor method will fail miserably. * Practical: Oooh, let's try it and see. Detour: Terminology: * Zeroary: No parameters * Unary: One parameter * Binary: Two parameter * Trinary/Ternary: Three parameter * N-ary: Lots of parameters (or unknown number) (or arbitrary number) Solution three: Think about funcctional programming * If we could pass (lambda () (new DoubleMachine(new GumballMachine()))) * Unfortunately, the bozos at Sun didn't think about higher-order functions (and they should have, since Guy Steele, who was on the Java design team, also designed Scheme) * OO Solution: Factories! * A factory is an object whose main purpose is to build other objects. Homework: * For Friday: Design and implement your own thing that uses factories. * For Monday: Look up "anonymous inner class"