Observer Project Pattern on Android

1

Would anyone like to show me an Observer structure inside the android?

I was trying to build an equal to java, but I did not succeed.

My test was done as follows:

  • I created a class Banco and a class ClienteObservable ;
  • In the database I have the notification methods, and adicionarObserver (I pass the ball to clienteObservable );
  • In class ClienteObservable I have the update method, which will perform an action upon being notified.

This is the logic I have about Observer Project Pattern, however I do not know how to structure this in , could anyone develop something pretty basic to show me?

The following is the code below:

In the Class Bank

IntheObservableclientclass

    
asked by anonymous 24.03.2014 / 19:45

1 answer

1

I think it's the same as java.

public class Cliente {
}
public interface ClienteObservable {
    public void update();
}
public class Banco {
    private List<ClienteObservable> observables = new ArrayList<ClienteObservable>();
    public void adicionarObserver(ClienteObservable obs){
       this.observables.add(obs);
    }
}

But there is a conceptual error here. In fact it should look like this:

public interface ClienteObserver {
    public void update(Cliente cliente);
}
public class Banco implements ClienteObserver {
    @Override
    public void update(Cliente cliente) {
        //faz algum calculo para o cliente  ..
    }
}
public class Cliente {
    private String nome;
    private List<ClienteObserver> observers = new ArrayList<ClienteObserver>();

    public void adicionarObserver(ClienteObserver obs) {
        this.observers.add(obs);
    }
    public void setNome(String nome) {
        this.nome = nome;
        this.notifyObservers();
    }
    private void notifyObservers() {
        for (ClienteObserver observer : this.observers) {
            observer.update(this);
        }
    }
}

For who you are observing is the Client object. When it updates its state it should communicate the observers about this modification.

    
24.03.2014 / 20:28