The nature of the observer and the violation of the principle of shared responsibility

I have an applet that redraws after changing the text.

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 } 

Is this not a violation of the principle of single responsibility (SRP), where my applet not only acts as an applet, but also has to do work with the listener. Similarly, the DynamicText class not only generates dynamic text, but also updates 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 violation of SRP?

Q2. Is composition the best choice here to remove the SRP violation, as in project 2.

+4
source share
2 answers

Q1: Yes.

Q2: Yes.

My own question is: is this some kind of sensible survey to get people to use the best design methods?

Anyway. What you are doing is recognizing that there is an intermediary pattern in your problem. This is subtle. Right now, it looks like it might be an adapter, but as your design grows, I suspect it will become clear that this is really a middleman. The reseller has many user interface issues. So much, in fact, that people made it possible to reconcile the Mediator's forces present in user interface problems, a special name: "MVC."

+1
source

I do not see a problem with SPR with design 1 as it is written. In MVC, the view must listen to the model, in which case the view is an applet, and the model is the publisher.

Now everything is in order, applets have a few more responsibilities (depending on the lifetime), which may mean that you want to separate a certain presentation class when you start to process them. Then the applet could use the composition view.

0
source

Source: https://habr.com/ru/post/1310445/


All Articles