82 lines
1.7 KiB
Python
82 lines
1.7 KiB
Python
"""
|
|
实例:
|
|
汤宝宝坚信搭积木是人类的未来,因此开办了一家积木厂。
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
|
|
# 抽象Node接口 Shape
|
|
class Shape(ABC):
|
|
@abstractmethod
|
|
def accept(self, visitor: "Visitor"):
|
|
pass
|
|
|
|
@abstractmethod
|
|
def claim_shape(self):
|
|
pass
|
|
|
|
|
|
class Circle(Shape):
|
|
def accept(self, visitor):
|
|
visitor.visit_circle(self)
|
|
|
|
def claim_shape(self):
|
|
print("I am a Circle")
|
|
|
|
|
|
class Square(Shape):
|
|
def accept(self, visitor):
|
|
visitor.visit_square(self)
|
|
|
|
def claim_shape(self):
|
|
print("I am a Square")
|
|
|
|
|
|
class Triangle(Shape):
|
|
def accept(self, visitor):
|
|
visitor.visit_triangle(self)
|
|
|
|
def claim_shape(self):
|
|
print("I am a Triangle")
|
|
|
|
|
|
# 抽象Visitor接口
|
|
class Visitor(ABC):
|
|
@abstractmethod
|
|
def visit_circle(self, circle: Circle):
|
|
pass
|
|
|
|
@abstractmethod
|
|
def visit_square(self, square: Square):
|
|
pass
|
|
|
|
@abstractmethod
|
|
def visit_triangle(self, triangle: Triangle):
|
|
pass
|
|
|
|
|
|
# 具体Visitor实现
|
|
class ShapeVisitor(Visitor):
|
|
def visit_circle(self, circle: Circle):
|
|
print("Visiting Circle:", end=" ")
|
|
circle.claim_shape()
|
|
|
|
def visit_square(self, square: Square):
|
|
print("Visiting Square:", end=" ")
|
|
square.claim_shape()
|
|
|
|
def visit_triangle(self, triangle: Triangle):
|
|
print("Visiting Triangle:", end=" ")
|
|
triangle.claim_shape()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("========== 访问者模式 ==========")
|
|
shapes = [Circle(), Square(), Triangle()]
|
|
visitor = ShapeVisitor()
|
|
for shape in shapes:
|
|
shape.accept(visitor)
|
|
|
|
print("\n======== 访问者模式结束 ========")
|