[设计模式]观察者模式, Observer

package pattern.observer; import java.util.Observable; public class Teacher extends Observable { public void askQuestion(){ System.out.println("Teacher: ask a question..."); setChanged(); notifyObservers(); } }

 

package pattern.observer; import java.util.Observable; import java.util.Observer; public class Student implements Observer { @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub System.out.println("Student: hands up"); } public static void main(String args[]){ Teacher t = new Teacher(); t.addObserver(new Student()); t.askQuestion(); } }

 

 

=================================================================

 

 

package pattern.observer; public interface ActionListener { public void actionPerformed(); }

 

 

 

package pattern.observer; import java.util.ArrayList; public class Button { private ArrayList<ActionListener> listeners = new ArrayList<ActionListener>(); public void addActionListener(ActionListener l){ listeners.add(l); } public void click(){ for(ActionListener l: listeners){ l.actionPerformed(); } } }

 

package pattern.observer; import java.text.*; import java.util.*; public class Frame implements ActionListener{ private Button b = new Button(); public Frame(){ b.addActionListener(this); } public void actionPerformed(){ System.out.println("click button at " + new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date())); } public void clickButton(){ b.click(); } public static void main(String args[]){ new Frame().clickButton(); } }

你可能感兴趣的:(设计模式,String,Class,import,button,interface)