■ 事例:Java

 ↑ TOP

☞ Key Point 情報隠蔽の原則


  • [54-67]作成者(プログラマー)は、特定のイベントに依存する箇所を抽出して、独立したインターフェース/抽象クラスを規定します。
  • [44-49]利用者(プログラマー)は、final 宣言が不要になります。


    
tips350_MouseClicked/java/src/AppWindow.scala
1: /* 2: * Copyright (c) 2010-2013, KOTSUBU-chan and/or its affiliates. 3: * Copyright (c) 1998, Atelier-AYA. 4: * All rights reserved. 5: */ 6: package cherry.pie; 7: 8: import java.awt.*; 9: import java.awt.event.*; 10: import javax.swing.*; 11: 12: // ---------------------------------------- 13: public class AppWindow extends JFrame { 14: static String version = AppWindow 15: .class.getName() + ": #1.0.01"; 16: // ---------------------------------------- 17: static void example() { 18: JFrame frame = new AppWindow("JTextField"); 19: frame.add(new View(frame)); 20: frame.pack(); 21: frame.setVisible(true); 22: } 23: 24: // ---------------------------------------- 25: AppWindow(String title) { 26: super(title); 27: setLocationRelativeTo(null); 28: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 29: } 30: } 31: 32: // ---------------------------------------- 33: /* note: error 34: * ---------------------------------------- 35: * ローカル変数 frame は内部クラスからアクセスされます。final で宣言される必要があります。 36: * frame.setTitle(p.toString()); 37: * ^ 38: */ 39: class View extends JPanel { 40: private JFrame frame; 41: View(JFrame frame) { 42: this.frame = frame; 43: setPreferredSize(new Dimension(260,100)); 44: new MouseClicked() { 45: public void execute(Point p) { 46: ((View)source).frame.setTitle(p.toString()); 47: // frame.setTitle(p.toString()); *1 48: } 49: }.listenTo(this); 50: } 51: } 52: 53: // ---------------------------------------- 54: interface Reactor { 55: public void execute(Point p); 56: } 57: abstract class MouseClicked extends MouseAdapter 58: implements Reactor { 59: public void mouseClicked(MouseEvent e) { 60: execute(e.getPoint()); 61: } 62: protected JComponent source; 63: public void listenTo(JComponent comp) { 64: comp.addMouseListener(this); 65: source = comp; 66: } 67: }

 ↑ UP

*1:☞ Key Point 情報隠蔽の原則