250 likes | 351 Views
CSC 313 – Advanced Programming Topics. Lecture 14: Factory Pattern Basics. Strategy Pattern Usage. public class RubberDuck extends Duck { FlightBehavior flyBehavior ; QuackBehavior quackBehavior ; public RubberDuck () { quackBehavior = new Squeak(); flyBehavior = new FlyNoWay (); }.
E N D
CSC 313 – Advanced Programming Topics Lecture 14:Factory Pattern Basics
Strategy Pattern Usage public class RubberDuck extends Duck {FlightBehaviorflyBehavior;QuackBehaviorquackBehavior;public RubberDuck() {quackBehavior = new Squeak();flyBehavior = new FlyNoWay(); }
Strategy Pattern Usage public class RubberDuck extends Duck {FlightBehaviorflyBehavior;QuackBehaviorquackBehavior;public RubberDuck() {quackBehavior = new Squeak();flyBehavior = new FlyNoWay(); } RubberDuck FlyNoWay Squeak
Decorator Pattern Usage Pizza pie = new DeepDish(); pie = new Garlic(pie); pie = new Garlic(pie); pie = new Onion(pie); Onion Garlic Garlic DDish pie
Zen & the Art of Programming Identify and isolate what will change from what stays the same Favor composition over inheritance Classes should be open for extension, but closed to modification Program to a concept, not a class
Zen & the Art of Programming Identify and isolate what will change from what stays the same Favor composition over inheritance Classes should be open for extension, but closed to modification Program to a concept, not a class
Zen & the Art of Programming Identify and isolate what will change from what stays the same Favor composition over inheritance Classes should be open for extension, but closed to modification Program to a concept, not a class
Zen & the Art of Programming Identify and isolate what will change from what stays the same Favor composition over inheritance Classes should be open for extension, but closed to modification Program to a concept, not a class
Zen & the Art of Programming Identify and isolate what will change from what stays the same Favor composition over inheritance Classes should be open for extension, but closed to modification Program to a concept, not a class
Programming to a Concept • Can we even make instantiation conceptual? • Hard-coded class name required by new command • Tricks impossible – no interfaces or abstract classes • Cannot rely on polymorphism
Programming to a Concept • Can we even make instantiation conceptual? • Hard-coded class name required by new command • Tricks impossible – no interfaces or abstract classes • Cannot rely on polymorphism • Must instantiate a class, but can LOOK fancy: new Squeak();new Garlic(pie);new Monkey(Oohhh, Look);
Decorator Pattern Problem Need DoubleGarlicOnionDeepDish class for this? Pizza pie = new Garlic(DeepDish()); pie = new Onion(Garlic(pie));
Strategy Pattern Usage Why write a class that just a constructor? public RubberDuck() {quackBehavior = new Squeak();flyBehavior = new FlyNoWay(); }
Relations Between Patterns • Design patterns can be used alone • Intent & purpose differs for each pattern • “Official” patterns in at least 3 industrial projects • Often travel together in code • Many strong relationships between patterns • Combination stronger than using by itself
Improving Constructor • May want to limit creating objects • Control instantiation and when or how it occurs • May want to enforce limit on number instantiated • Boolean instances silly, for example • Wastes time & memory, only have 2: true&false • Constructors limited in their actions, however • Before constructor starts, instance already allocated • Exception only option to disrupt allocation process
Smarter Move public class Bool {staticBool TRUE = new Bool(true);staticBool FALSE = new Bool(false);private booleanvalue;privateBool(boolean b) {value = b;}staticBoolfromBoolean(boolean b) {if (b) return TRUE; elsereturn FALSE; }
Cache Data To Save Time public class Int {staticMap<String,Int> map; intvalue;privateInt(inti){ value= i; }publicIntfromString(String s) {IntretVal=map.get(s);if (retVal == null) {retVal=newInt(Integer.parseInt(s));map.put(s,retVal); }returnretVal;}
Smart Instantiation • To limit construction what should your code do • Make sure you declare constructors protected/private • Get instances via method declared public static • From outside class, instantiation is prohibited • Get protection error on lines with newcommand • For instance, mustuse publicstaticmethod
Better Instantiation • Methods like these called Factory Methods • Method creates objects just like it is a factory • Factory methods provide additional features • Meaningful name can be given to method • Using set of methods, creation options clarified • Readable code easy & no jumping through hoops
Factory Method Example public class Int {staticMap<String,Int> map; intvalue;privateInt(inti){ value= i; }publicIntfromString(String s) {IntretVal=map.get(s);if (retVal == null) {retVal=newInt(Integer.parseInt(s));map.put(s,retVal); }returnretVal;}
Simple Factory Pattern • Also known as Static Factory Pattern • (Only if method static& not instance based) • Pattern uses single factory method as base • Multiple types instantiated in factory method • Contains specific, hard-coded “new” commands • Other classes use method to skip instantiations • Changing or adding types is much easier • Only need to modify factory method • Client code may not know other types exist!
Static Factory Method public class StaticFactory{static Pizza createPizza(String type) {if (type.equals(“cheese”)) {return new CheesePizza();} else if (type.equals(“fish”)) { return new AnchovyPizza(); } else { throw Exception(“No Pizza for you!”); } } Pizza pie = StaticFactory.createPizza(“fish”);
Simple Factory Method public class SimpleFactory{Pizza createPizza(String type) {if (type.equals(“cheese”)) {return new CheesePizza();} else if (type.equals(“fish”)) { return new AnchovyPizza(); } else { throw Exception(“No Pizza for you!”); } } SimpleFactory simple = ... Pizza pie = simple.createPizza(“fish”);
Creating Simple Factory • Factory method instantiates many types • protectedconstructors prevents unlimited alloc. • Within method,parameter(s) specify what to allocate • Pluses & minuses to static factory method use • Factory method much easier to find and call • Client tied to factory class via hard-coded call • Keeping factory method non-static means • More generic client code calling factory method • Exactly which method called not clear
For Next Lecture • Lab #3 available on Angel • Asks you to implement Decorator Pattern • Have time today, butmay want help profiling • In your book, read pages 123 - 143 • How do we write these factories? • Is there a good way to do this? • What design pattern could be used in these cases?