我制作的解决方案如下:
创建了一个简单的界面:
public interface Follower {
public void changed(String property);
}
和一个监听器类:
public class LogoListener {
/**
* A static reference to this.
*/
private static LogoListener listener;
/**
* Represents the objects to be notified by the listener.
*/
private static List<Follower> followers;
/**
* Create a simple listener to be used by one "notifying"
* object, and "followers" objects.
*
*/
private LogoListener() {
followers = new ArrayList<Follower>();
listener = this;
}
/**
* Method to be used by the "notifying" object, to
* notify followers.
*/
public void notifyFollowers() {
for(Follower follower : followers){
follower.changed("Logo changed");
}
System.out.println("Logo changed");
}
/**
* Get the listener instance, or create one if it does not exist.
*
* @return the listener
*
*/
public static LogoListener getListener() {
if(listener == null) {
listener = new LogoListener();
}
return listener;
}
/**
*
* @param follower
* <br>Not null.
* @throws
* <br>IllegalArgumentException if <code>follower</code> is null.
*/
public void addFollower(Follower follower) {
if(follower == null ) {
throw new
IllegalArgumentException("Follower should not be null");
}
followers.add(follower);
}
}
报告面板(“追随者”或监听对象)实现了追随者接口,这只是意味着覆盖 changed(String message) 方法:
/* (non-Javadoc)
* @see listener.Follower#changed(java.lang.String)
*/
@Override
public void changed(String msg ) {
//respond to change goes here
System.out.println(msg);
}
并通过以下方式注册为关注者:
LogoListener.getListener()
.addFollower(this);
徽标面板通过以下方式通知更改:
LogoListener listener = LogoListener.getListener();
listener.notifyFollowers();
Commnets 和反馈是最受欢迎的。