zoukankan      html  css  js  c++  java
  • Java-马士兵设计模式学习笔记-观察者模式-模拟Awt Button

    一、概述

    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存放Listener
    20     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     @Override
    41     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     @Override
    51     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 }

    三、运行结果

  • 相关阅读:
    散户必看 教您怎样在短期内从10万炒到100万
    店主学习篇 如何做服装经营能手
    苹果公司CEO乔布斯在斯坦福大学毕业典礼上的演讲
    手头20万存款的租客 买房划算还是租房省钱?
    把幸福 亲了又亲
    周经理写给公司 的一封信
    土鸡市场前景:
    查看局域网内所有IP
    中国肿瘤年报出炉 浙江每312人就有1人患癌
    中药材喂土鸡或许大家还很疑惑吧
  • 原文地址:https://www.cnblogs.com/shamgod/p/4590378.html
Copyright © 2011-2022 走看看