访问者模式

菜鸟教程 · · 66 次点击 · · 开始浏览    

Python 代码:

# Visitor Pattern with Python Code
from abc import abstractmethod,ABCMeta
# 定义一个表示元素(Element)的接口
class ComputerPart(metaclass=ABCMeta):
    @abstractmethod
    def accept(self, inComputerPartVisitor):
        pass
#创建阔爱站了ComputerPart的实体类
class Keyboard(ComputerPart):
    def accept(self, inComputerPartVisitor):
        inComputerPartVisitor.visitKeyboard(self)
class Monitor(ComputerPart):
    def accept(self, inComputerPartVisitor):
        inComputerPartVisitor.visitMonitor(self)
class Mouse(ComputerPart):
    def accept(self, inComputerPartVisitor):
        inComputerPartVisitor.visitMouse(self)
class Computer(ComputerPart):
    _parts = []
    def __init__(self):
        self._parts.append(Mouse())
        self._parts.append(Keyboard())
        self._parts.append(Monitor())
    def accept(self, inComputerPartVisitor):
        for aPart in self._parts :
            aPart.accept(inComputerPartVisitor)
        inComputerPartVisitor.visitComputer(self)
# 定义一个表示访问者的接口
class ComputerPartVisitor(metaclass=ABCMeta):
    @abstractmethod
    def visitComputer(self,inComputer):
        pass
    @abstractmethod
    def visitMouse(self,inMouse):
        pass
    @abstractmethod
    def visitKeyboard(self,inKeyboard):
        pass
    @abstractmethod
    def visitMonitor(self,inMonitor):
        pass
# 实现访问者接口的实体类
class ComputerPartDisplayVisitor(ComputerPartVisitor):
    def visitComputer(self,inComputer):
        print("Displaying {0}. Called in {1}".format(inComputer.__class__.__name__,self.__class__.__name__))
    def visitMouse(self,inMouse):
        print("Displaying {0}. Called in {1}".format(inMouse.__class__.__name__,self.__class__.__name__))
    def visitKeyboard(self,inKeyboard):
        print("Displaying {0}. Called in {1}".format(inKeyboard.__class__.__name__,self.__class__.__name__))
    def visitMonitor(self,inMonitor):
        print("Displaying {0}. Called in {1}".format(inMonitor.__class__.__name__,self.__class__.__name__))
# 调用输出
if __name__ == '__main__':
    aComputer = Computer()
    aComputer.accept(ComputerPartDisplayVisitor())
Siskin.xu

   Siskin.xu

  sis***@sohu.com

5个月前 (03-10)

本文来自:菜鸟教程

感谢作者:菜鸟教程

查看原文:访问者模式

66 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传