1 / 25

Lecture 14: Factory Pattern Basics

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 (); }.

omana
Download Presentation

Lecture 14: Factory Pattern Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 313 – Advanced Programming Topics Lecture 14:Factory Pattern Basics

  2. Strategy Pattern Usage public class RubberDuck extends Duck {FlightBehaviorflyBehavior;QuackBehaviorquackBehavior;public RubberDuck() {quackBehavior = new Squeak();flyBehavior = new FlyNoWay(); }

  3. Strategy Pattern Usage public class RubberDuck extends Duck {FlightBehaviorflyBehavior;QuackBehaviorquackBehavior;public RubberDuck() {quackBehavior = new Squeak();flyBehavior = new FlyNoWay(); } RubberDuck FlyNoWay Squeak

  4. Decorator Pattern Usage Pizza pie = new DeepDish(); pie = new Garlic(pie); pie = new Garlic(pie); pie = new Onion(pie); Onion Garlic Garlic DDish pie

  5. 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

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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);

  12. Decorator Pattern Problem Need DoubleGarlicOnionDeepDish class for this? Pizza pie = new Garlic(DeepDish()); pie = new Onion(Garlic(pie));

  13. Strategy Pattern Usage Why write a class that just a constructor? public RubberDuck() {quackBehavior = new Squeak();flyBehavior = new FlyNoWay(); }

  14. 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

  15. 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

  16. 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; }

  17. 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;}

  18. 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

  19. 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

  20. 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;}

  21. 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!

  22. 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”);

  23. 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”);

  24. 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

  25. 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?

More Related