Observer pattern and violation of Single Responsibility Principle
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开发者_如何学C, 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 (SRP) 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 SRP violation?
Q2. Is composition a better choice here to remove SRP violation as in design 2.
Q1: Yes.
Q2: Yes.
My own question: is this some sort of push-poll to get people using better design techniques?
Anyway. What you are doing is recognizing that there is also a Mediator pattern in your problem. It's subtle. Right now, it looks like it could be an Adapter but, as your design grows, I suspect it will become clear that this is really a Mediator. Mediator is in a lot of UI problems. So many, in fact, that people have given reconciling the Mediator forces present in UI problems a special name: "MVC."
I don't really see an SPR problem with design 1 as it is written. In MVC the view should listen to the model, and in this case the view is the applet and the publisher is the model.
Now OK, applets have a few other responsibilities (lifetime management springs to mind) which might mean you want to separate out a specific view class when you start to handle those. The applet could then use the view by composition.
精彩评论