jeudi 11 février 2016

What can I use instead of "this" as passing argument?

I am actually new to Design Pattern concepts and am trying to implement the Observer Pattern.

I have a Blog class which notifies observers of new changes.It implemets Subject interface. It has a registerObserver method for adding new observers. On the other hand, I have classes for different kinds of observers which all implement the Observer interface.

I want to have a Register method and a Unsubscribe method in observer classes so that they can choose when to be added and removed. However, when I use my code that I have written here, I get a Null Pointer Exception error in runtime which is apparently because of the line blog.registerObserver(this).

What other options do I have in order to implement Register and Unsubscribe methods?

public void registerObserver( Observer o) //when an observer resgiters we add 
                                          // it to the end of the list
{
    observers.add(o);
}

Observer is an interface and client classes implement it. Now I have a class of ClientForMusic:

public class ClientForMusic implements Observer, DisplayElement {

private String Music;
private Subject blog;
public ClientForMusic()
{}

public void Register (Subject Blog)
{
   this.blog=blog;
   blog.registerObserver(this);  
}

public void Unsubscribe(Subject Blog)
{
    this.blog=blog;
    blog.removeObserver(this);
}


public void update(String music, String movie, String news, String science )
{
    this.Music= music;
    display();
}

public void display()
{
     System.out.println("I have been notified of a new song:" + Music);
}
}

Aucun commentaire:

Enregistrer un commentaire