例題で学ぶデザインパターン #18:デザインパターン〈GoF〉Visitor, #2
例題で学ぶ Jython/Swing デザインパターン《Jython2.5》
デザインパターン〈GoF〉Visitor
《著》越智ことり+小粒ちゃん《監修》小泉ひよ子とタマゴ倶楽部
第1版♪2003/05/23 ● 第2版♪2009/04/03
■ 概要
例題により、アプリケーションを作成する過程を通して、Jython/Swing によるデザインパターンを習得します。
この課題では、Swing/GUI を使って階層構造を持つ情報を提示します。〈GoF〉Composite/Iterator/Visitor/Command パターンを導入すると、if/for 文によるコードの汚染、配列の境界問題が解消されるので、要求仕様の変更にも柔軟に対処でき、簡潔で見通しの良いコードを記述できるようになります。
《Note》JPython1.1.x/Jython2.1.x 用に作成したセミナー課題を、Jython2.5 で再構成しました。
事例:コードの解説
■ モジュール:TreeCommand.py
... from TreeVisitor import TextVisitor, TreeVisitor class TreeCommand(Command): def __call__(self): path = self.view.lastSelectedPathComponent model = path.userObject visitor = TreeVisitor(model) model.accept(visitor, visitor.root) view = JTree( visitor.root, valueChanged = self.view.valueChanged, ) ... class TextCommand(Command): def __call__(self): path = self.view.lastSelectedPathComponent model = path.userObject visitor = TextVisitor() model.accept(visitor, visitor.root) view = JTextArea( font = Font("Courier", Font.PLAIN, 12), text = str(visitor.root), ) ... ## ---------------------------------------- class PopWindow(JFrame): def __init__(self, **keys): super(self.__class__,self).__init__( defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE, **keys) def open(self, x=900, y=200, w=200, h=150): self.bounds = x, y, w, h self.visible = True ## ========================================
■ モジュール:TreeComposite.py
class TreeNode(object): def accept(self, visitor, parent): raise NotImplementedError(self.__class__.__name__) class Leaf(TreeNode): def accept(self, visitor, parent): visitor.visitLeaf(self, parent) class Node(TreeNode): def accept(self, visitor, parent): visitor.visitNode(self, parent)
■ モジュール:TreeView.py
... from TreeVisitor import TextVisitor class View(JPanel): def valueChanged(self, e): model = e.path.lastPathComponent.userObject visitor = TextVisitor() model.accept(visitor, visitor.root) self.textArea.text = str(visitor.root)
Tips
》作業中です《
Last updated♪09/06/16