return remaining_string[i_start_tag:class closetagdef process(selfremaining_stringparser)i_start_tag remaining_string find('<'i_end_tag remaining_string find('>'assert remaining_string[i_start_tag+ ="/tag_name remaining_string[i_start_tag+ :i_end_tagassert tag_name =parser current_node tag_name parser current_node parser current_node parent parser state child_node return remaining_string[i_end_tag+ :strip(first_tag firsttag(child_node childnode(text_node textnode(open_tag opentag(close_tag closetag(all we've done is create instances of the various state classes that can be reused notice how we can access these module variables inside the classeseven before the variables have been definedthis is because the code inside the classes is not executed until the method is calledand by this pointthe entire module will have been defined the difference in this example is that instead of wasting memory creating bunch of new instances that must be garbage collectedwe are reusing single state object for each state even if multiple parsers are running at onceonly these state classes need to be used when we originally created the state-based parseryou may have wondered why we didn' pass the parser object to __init__ on each individual stateinstead of passing it into the process method as we did the state could then have been referenced as self parser this is perfectly valid implementation of the state patternbut it would not have allowed leveraging the singleton pattern if the state objects maintain reference to the parserthen they cannot be used simultaneously to reference other parsers rememberthese are two different patterns with different purposesthe fact that singleton' purpose may be useful for implementing the state pattern does not mean the two patterns are related