var data = 0 val frame = new JFrame("SAM Testing") val jButton = new JButton("counter") /* * java实现方式 * 该方式中,每次都要进行new ActionListener,actionPerformed这些样板动作 * 而我们真正关心的是button被点击的时候,所发生的业务逻辑 * 这就是该方式的最大的问题 */ jButton.addActionListener(new ActionListener { override def actionPerformed( event: ActionEvent){ data += 1 println(data) } }) /* * scala sam的实现方式 * 该方式中,我们做了一个隐式转换,这个隐式转换是如何工作的呢?? * 第一步:首先定义隐式转换函数,convertedAction * 该函数将action: (ActionEvent) => Unit) 映射到 函数的定义上,即 * new ActionListener {省略} * 第二步:将函数的逻辑传入sam砖转换函数中 */ implicit def convertedAction( action: (ActionEvent) => Unit) = new ActionListener { override def actionPerformed(event: ActionEvent) {action(event)} } jButton.addActionListener((event:ActionEvent)=>{data+=1;println(data)}) frame.setContentPane(jButton) frame.pack() frame.setVisible(true)
