web123456

Python design pattern: factory pattern

Design Pattern 1: Factory Pattern

What is the factory model

According to the information provided, the desired result is returned to the factory process.
For example, Party A provides the factory with a shape requirement and the shape is a duck. There are many molds in the factory, including ducks, puppies, kittens, etc. After receiving the request, the factory selected the duck mold according to the requirements and returned it to Party A.

Usage features

1. Request an object without knowing where the object comes from, simplifying the creation of the object
2. Similar object creation can be grouped through factory mode
3. Multiple factories can be created, each factory is responsible for one task

Use scenarios

1. The object code created by the application is distributed in multiple different places, rather than in a function/method, and these objects cannot be tracked.
2. It is necessary to decouple the creation and use of objects
3. Consider improving performance and memory usage, and create new objects when necessary (direct instantiation of creating objects will allocate additional memory)

Example code

class MP3:
    def __init__(self,filepath):
        self.playdata = filepath[:-4]

    def play(self):
        return self.playdata

class MP4:
    def __init__(self,filepath):
        self.playdata = filepath[:-4]

    def play(self):
        return self.playdata

def Play_Factory(filepath):
    if filepath[-3:] == 'mp3':
        machine = MP3(filepath)
    elif filepath[-3:] == 'mp4':
        machine = MP4(filepath)
    return machine

#Package the factory method and add exception handling
def Play_machine(filepath):
    machine = None
    try:
        machine = Play_Factory(filepath)
    except BaseException as ve:
        print(ve)
    return machine

if __name__ == "__main__":
    music = Play_machine('lalalalala.mp3')
    data = music.play()
    print('music data is {}'.format(data))
    move = Play_machine('dadadadadada.mp4')
    data = move.play()
    print('move data is {}'.format(data))
    game = Play_machine('')