Observer pattern and violation of Single Responsibility Principle

Posted by Devil Jin on Stack Overflow See other posts from Stack Overflow or by Devil Jin
Published on 2010-05-21T02:22:50Z Indexed on 2010/05/21 14:20 UTC
Read the original article Hit count: 251

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about best-practices