Python 解析器模式

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 29 19:26:13 2018

@author: mz
"""

class Context(object):
    def SetContect(self, rhs):
        self.context = rhs
    def GetContext(self):
        return self.context


class Interpretor(object):
    def Interprets(self, context):
        pass        

class IntegerInterpretor(Interpretor):
    def Interprets(self, context):
        for c in context.GetContext():            
            if c.isdigit():
                print("i")
            else:
                print("-")


class StringInterpretor(Interpretor):
    def Interprets(self, context):
        for c in context.GetContext():  
            if c.isalpha():
                print("s")
            else:
                print("-")


if "__main__" == __name__:
    context = Context()
    context.SetContect("1234zhnlksdf888")
    
    interpretors = [IntegerInterpretor(), StringInterpretor()]
    
    for interpretor in interpretors:
        print("\r\n--------")
        interpretor.Interprets(context)
    
    
    
    

运行结果:

--------
i
i
i
i
-
-
-
-
-
-
-
-
i
i
i

--------
-
-
-
-
s
s
s
s
s
s
s
s
-
-
-

猜你喜欢

转载自blog.csdn.net/mz5111089/article/details/79748097