Informatics 122 Software Design II: Emily Navarro
Informatics 122 Software Design II: Emily Navarro
Software Design II
Lecture 5
Emily Navarro
Duplication of course material for any commercial purpose without the explicit written permission of the professor is prohibited.
1
Announcement
• In addition, if you have code that instantiates a particular subtype based on the
current state of the program, then the code depends on each concrete class
if (hunting) {
return new DecoyDuck() Obvious problems:
} else { needs to be recompiled each time a
return new RubberDuck() dependent changes;
} add new classes -> change this code
remove existing classes -> change this
code
PizzaStore Example
Pizza
• Each franchise needs its own factory to match the proclivities of the locals
• However, we want to retain the preparation process that has made PizzaStore
such a great success
Nice and simple. If you want a NY-style pizza, you create an instance of
this class and call orderPizza() passing in the type. The subclass makes
sure that the pizza is created using the correct style.
17
Demo
Factory Method: Definition and
Structure
• The Factory Method design pattern defines an interface
for creating an object, but lets subclasses decide which
class to instantiate. Factory Method lets a class defer
instantiation to subclasses.
Duck
swim()
display()
setFlyBehavior(FlyBehavio
FlyWithWings CantFly r) Silence Quack Squeak
fly() fly() setQuackBehavior(QuackB quack() quack() quack()
ehavior)
performFly()
performQuack()
Note the introduction of more abstract classes: Dough, Sauce, Cheese, etc.
Second, we Implement a
Region-Specific Factory
This factory ensures that quality
ingredients are used during the
pizza creation process…
First, alter the Pizza abstract base class to make the prepare method
abstract…
Within Pizza Subclasses… (II)
• Our client code (PizzaStore) can then pick the factory appropriate
to its region, plug it in, and get the correct style of pizza (Factory
Method) with the correct set of ingredients (Abstract Factory)
Demo
Class Diagram of Abstract
Factory Solution
30
Abstract Factory: Definition
and Structure
• The Abstract Factory design pattern provides an
interface for creating families of related or dependent
objects without specifying their concrete classes
Abstract Factory
Characteristics
• Isolates concrete classes
• 24
• 4
• 25
• 16
• 13
Reflection