Design Patterns - 6.5 - Builder Pattern
Design Patterns - 6.5 - Builder Pattern
Design Patterns
LECTURE 6 ½ - BUILDER PATTERN
DR. JOSHUA WAXMAN
2
Basic Idea
Have a Java object with many attributes. The constructor would need (perhaps) to take all
of them. Too many to remember.
What if don’t want to specify all of them?
What if don’t want to specify them in order?
Java does not have optional parameters. Java does not have keyword parameters.
class GameCharacter(object):
def __init__(self, name, hitPoints, intelligence, strength):
self.name = name
self.hitPoints = hitPoints
self.intelligence = intelligence
self.strength = strength
main()
5
In Python – with keyword parameters
class GameCharacter(object):
def __init__(self, name, hitPoints, intelligence, strength):
self.name = name
self.hitPoints = hitPoints In any order, readable!
self.intelligence = intelligence Java doesn’t allow.
self.strength = strength
def main():
gwaedhiel = GameCharacter(name='gwaedhiel', intelligence=50,
hitPoints=100, strength=10)
main()
6
In Python – with default parameters
Inner class Builder can directly access outer class, assign immediately (eagerly), in which
case build() just returns the built object
Or, it can be lazy, cache the values, and only make use of all of them when in place and
call build(), perhaps even calling the constructor of the outer class.