简体   繁体   中英

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);
}
}

It seems strange that your methods register and unsubscribe receive blog as a parameter. You either need to instantiate your blog at constructor of the Observer or have a setter method in your Observer that takes your blog. Or at least if you want to pass it through method register then keep it. Method unsubscribe should be using the same instance of blog that was used to register there. NPE probably occurs if you pass null value to your register or unsubscribe method. Otherwise your code looks OK

Your problem can be one of two:

1) Your observers variable is not initialized, so calling:

observers.add(o)

is throwing the exception. You need to initialize your "observers" variable, for example:

observers = new ArrayList()

2) Your variable "blog" in your "blog.registerObserver(this)" call is null in which case you should initialize your blog variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM