I have an applet which repaints itself once the text has changed
Design 1:
//MyApplet.java
public class MyApplet extends Applet implements Listener{
private DynamicText text = null;
public void init(){
text = new DynamicText("Welcome");
}
public void paint(Graphics g){
g.drawString(text.getText(), 50, 30);
}
//implement Listener update() method
public void update(){
repaint();
}
}
//DynamicText.java
public class DynamicText implements Publisher{
// implements Publisher interface methods
//notify listeners whenever text changes
}
Isn't this a violation of Single Responsibility Principle where my Applet not only acts as Applet but also has to do Listener job. Same way DynamicText class not only generates the dynamic text but updates the registered listeners.
Design 2:
//MyApplet.java
public class MyApplet extends Applet{
private AppletListener appLstnr = null;
public void init(){
appLstnr = new AppletListener(this);
// applet stuff
}
}
// AppletListener.java
public class AppletListener implements Listener{
private Applet applet = null;
public AppletListener(Applet applet){
this.applet = applet;
}
public void update(){
this.applet.repaint();
}
}
// DynamicText
public class DynamicText{
private TextPublisher textPblshr = null;
public DynamicText(TextPublisher txtPblshr){
this.textPblshr = txtPblshr;
}
// call textPblshr.notifyListeners whenever text changes
}
public class TextPublisher implments Publisher{
// implements publisher interface methods
}
Q1. Is design 1 a SPR violation?
Q2. Is composition a better choice here to remove SPR violation as in design 2.