Returning User-Defined Objects With Factory Patterns
00:00 In this lesson, we’ll look at how you can use the factory pattern to return user-determined objects. The factory pattern defines an interface for creating objects during program execution in response to conditions you can’t predict when writing your program.
00:17 You write a factory of user-defined objects with a function that takes some initialization arguments and returns different objects determined by input during the program execution. For example, in a painting program, you need to create different types of shapes in response to the user’s selection.
00:37 They might select to make a square one time, then a circle, then a rectangle, and so on and so forth. So the function you write for them to create something will have to return a different type of object each time they use it. So, what’s involved?
01:15 Then you write a function that takes as its first positional argument a string to provide the name of the shape to be created. Then it would take any additional arguments that might be needed to create that shape.
01:29 It uses a dictionary to match each possible shape name string with the actual class name it relates to. Then the proper class name is found by looking up its shape name key and the remaining arguments given to this function are provided to that shape class’s initializer. That new shape object is then returned to the calling environment. Here’s how it would all fit together.
First are the simple
Square classes. Both of these initializers just happen to take a single argument, but you can imagine other shape classes with initializers that need more than one. Here’s our
02:27 Since we’ve only defined two shape classes, our dictionary only needs two key-value pairs, each of the form string—key, class name—value. As we create additional shapes that the user can select, we would extend this dictionary to include them.
When I call this function to create a shape, we look up the shape name string in the dictionary, then use the class name it maps to to create type of object in our
return statement, passing the additional arguments to its initializer and then returning that newly created shape. For example, if we specify a
"circle", it’s as if this whole phrase is replaced with the name
Circle, and then its initializer using the remaining parameters.
Become a Member to join the conversation.