25
LECTURE 14: FACTORY PATTERN BASICS CSC 313 – Advanced Programming Topics

CSC 313 – Advanced Programming Topics. Strategy Pattern Usage public class RubberDuck extends Duck { FlightBehavior flyBehavior; QuackBehavior quackBehavior;

Embed Size (px)

Citation preview

LECTURE 14:FACTORY PATTERN BASICS

CSC 313 – Advanced Programming Topics

Strategy Pattern Usage

public class RubberDuck extends Duck {

FlightBehavior flyBehavior;QuackBehavior quackBehavior;

public RubberDuck() { quackBehavior = new Squeak(); flyBehavior = new FlyNoWay();

}

Strategy Pattern Usage

public class RubberDuck extends Duck {

FlightBehavior flyBehavior;QuackBehavior quackBehavior;

public RubberDuck() { quackBehavior = new Squeak(); flyBehavior = new FlyNoWay();

}

flyBehaviorquackBehavior

Squeak

FlyNoWayRubberDuck

Decorator Pattern Usage

Pizza pie = new DeepDish();

pie = new Garlic(pie);

pie = new Garlic(pie);

pie = new Onion(pie);

Onion

Garlic

GarlicDDish

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 {static Bool TRUE = new Bool(true);static Bool FALSE = new Bool(false);

private boolean value;

private Bool(boolean b) { value = b; }

static Bool fromBoolean(boolean b) { if (b) return TRUE; else return FALSE; }

Cache Data To Save Time

public class Int {static Map<String,Int> map;

int value;

private Int(int i) { value = i; }

public Int fromString(String s) { Int retVal = map.get(s); if (retVal == null) { retVal = new Int(Integer.parseInt(s)); map.put(s, retVal); } return retVal;}

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 new

command For instance, must use public static

method

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 {static Map<String,Int> map;

int value;

private Int(int i) { value = i; }

public Int fromString(String s) { Int retVal = map.get(s); if (retVal == null) { retVal = new Int(Integer.parseInt(s)); map.put(s, retVal); } return retVal;}

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 protected constructors 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, but may 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?