专业的编程技术博客社区

网站首页 > 博客文章 正文

用python实现软件设计模式之访问者模式

baijin 2024-10-01 07:32:55 博客文章 8 ℃ 0 评论

前言

访问者模式,表示一个作用于某个对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

代码

class Action:
    def Get_Man_Conclusion(self, concrete_element_A):
        pass

    def Get_Woman_Conclusion(self, concrete_element_B):
        pass

class Person:
    def Accept(self, visitor : Action):
        pass

class Man(Person):
    def Accept(self, visitor : Action):
        visitor.Get_Man_Conclusion(self)

class Woman(Person):
    def Accept(self, visitor: Action):
        visitor.Get_Woman_Conclusion(self)

class Success(Action):
    def Get_Man_Conclusion(self, concrete_element_A):
        print(f"When {type(concrete_element_A).__name__} is {type(self).__name__},there is often a great woman behind him")
    
    def Get_Woman_Conclusion(self, concrete_element_B):
        print(f"When {type(concrete_element_B).__name__} is {type(self).__name__},there is probably an unsuccessful man behind him")

class Failing(Action):
    def Get_Man_Conclusion(self, concrete_element_A):
        print(f"When {type(concrete_element_A).__name__} is {type(self).__name__},no one needs to persuade him to drink alcohol")
    
    def Get_Woman_Conclusion(self, concrete_element_B):
        print(f"When {type(concrete_element_B).__name__} is {type(self).__name__},with tears in his eyes, no one can persuade him")

class Amativeness(Action):
    def Get_Man_Conclusion(self, concrete_element_A):
        print(f"When {type(concrete_element_A).__name__} is {type(self).__name__},he pretends to understand everything he doesn’t understand")
    
    def Get_Woman_Conclusion(self, concrete_element_B):
        print(f"When {type(concrete_element_B).__name__} is {type(self).__name__},she understands and pretends not to understand")

class Object_Structure:
    def __init__(self) -> None:
        self.elements = []

    def Attach(self, element : Person):
        self.elements.append(element)

    def Detach(self, element : Person):
        self.elements.remove(element)

    def Display(self, visitor):
        for e in self.elements:
            e.Accept(visitor)

if __name__ == '__main__':
    o = Object_Structure()
    o.Attach(Man())
    o.Attach(Woman())

    v1 = Success()
    o.Display(v1)

    v2 = Failing()
    o.Display(v2)

    v3 = Amativeness()
    o.Display(v3)

运行结果:



通过Object_Structure去维护所有的Person子类。Display接口用于传入具体的状态,比如Success,Failing,Amativeness。对于每个行为都会实现Get_Man_Conclusion和Get_Woman_Conclusion。而这两个接口又分别对应Man和Woman类去实际调用它。代码中Success,Failing,Amativeness都是具体的访问者。如果新增一个如Man一样的元素类,需要同时修改所有访问者类。

总结

访问者模式的目的是要把处理从数据结构分离出来,让算法和数据结构可以分开。

优点:增加新的操作很容易,因为增加新的操作就意味着增加一个新的访问者。

缺点:使得增加新的数据结构变得困难了。比如新增一个元素类,你需要修改所有的访问者类。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表