Java 類比Awt Button Observer模式

來源:互聯網
上載者:User

標籤:

一、概述

Java 的Awt是 Observer模式,現用Java自己類比awt中Button的運行機制

 

二、代碼

1.Test.java

 1 import java.text.DateFormat; 2 import java.text.SimpleDateFormat; 3 import java.util.ArrayList; 4 import java.util.Date; 5 import java.util.List; 6  7 public class Test { 8  9     public static void main(String[] args) {10         Button b = new Button();11         b.addActionListener(new MyActionListener1());12         b.addActionListener(new MyActionListener2());13         b.buttonPress();14     }15 }16 17 class Button {18     19     //用List存放Listener20     private List<ActionListener> actionListeners = new ArrayList<ActionListener>();21     22     public void addActionListener(ActionListener l) {23         actionListeners.add(l);24     }25     26     public void buttonPress(){27         ActionEvent e = new ActionEvent(System.currentTimeMillis(), this);28         for (ActionListener l : actionListeners) {29             l.actionPerformed(e);30         }31     }32 }33 34 interface ActionListener {35     public void actionPerformed(ActionEvent e);36 }37 38 class MyActionListener1 implements ActionListener {39 40     @Override41     public void actionPerformed(ActionEvent e) {42         System.out.println("MyActionListener1");43         System.out.println("事件發生時間:"+e.getTime()+" 事件來源:"+e.getSource());44     }45     46 }47 48 class MyActionListener2 implements ActionListener {49 50     @Override51     public void actionPerformed(ActionEvent e) {52         System.out.println("MyActionListener2");53         System.out.println("事件發生時間:"+e.getTime()+" 事件來源:"+e.getSource());54 55     }56     57 }58 59 class ActionEvent {60     61     private long time;62     private Object source;63     64     public ActionEvent(long time, Object source) {65         this.time = time;66         this.source = source;67     }68 69     public Object getSource() {70         return source;71     }72 73     public String getTime() {74 //        DateFormat df = new SimpleDateFormat("dd:MM:yy:HH:mm:ss");75         DateFormat df = new SimpleDateFormat("yyyy:MM:dd---HH:mm:ss");76         return df.format(new Date(time));77     }78     79     80 }

 

三、運行結果

Java 類比Awt Button Observer模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.