Java observer search sensor?

observer.update ();

The above method makes the GONE observers visible, but I want to change all other observers except the sending observer. How can I control this?

My actions are observers and are recorded in their constructor, as shown below,

public class ParentAction extends AbstractAction implements IActionObserver{ private ArrayList<IAction> lSubItems; private View subView; public ParentAction( String ItemText,int drawable,ArrayList<IAction> SubItems) { super(ItemText,drawable); lSubItems = SubItems; ActionHolder.getInstance().registerObserver(this); } @Override public void update() { getSubView().setVisibility(View.GONE); } ... 

Actionholder

 public class ActionHolder implements IActionSubject { private static ActionHolder uniqueActionHolder; private ArrayList observers; private ActionHolder() { observers = new ArrayList(); } public static synchronized ActionHolder getInstance() { if (uniqueActionHolder == null) { uniqueActionHolder = new ActionHolder(); } return uniqueActionHolder; } public void registerObserver(IActionObserver o) { observers.add(o); } public void removeObserver(IActionObserver o) { int i = observers.indexOf(o); if (i >= 0) { observers.remove(i); } } public void notifyObserver() { for (int i = 0; i < observers.size(); i++) { IActionObserver observer = (IActionObserver) observers.get(i); observer.update(); } } public void actionClicked(View view) { notifyObserver(); } } 
+4
source share
2 answers

Is this your own implementation of the observer pattern? If so, you can change the notify method, for example:

 public void notifyObserver(IAction sender) { for (int i = 0; i < observers.size(); i++) { IActionObserver observer = (IActionObserver) observers.get(i); if (observer != sender) observer.update(); } } 

and call it like

 ActionHolder.getInstance().notifyObserver(this); 

Alternatively , you can add a flag to your action class:

 private bool sender = false; 

set the flag before notification:

 sender = true; ActionHolder.getInstance().notifyObserver(); 

and use this flag in update :

 @Override public void update() { if (!sender) { getSubView().setVisibility(View.GONE); } sender = false; } 
+3
source

You raise an event in the actionClicked method, and then notify all observers. Just pass the link to your sending observer to skip updating it later.

If I understand your code correctly, you can achieve this by controlling the sender using view

 public void actionClicked(View view) { notifyObserver(view); } public void notifyObserver(View view) { for (int i = 0; i < observers.size(); i++) { IActionObserver observer = (IActionObserver) observers.get(i); observer.update(view); } } 

And the update method skips the current view

 @Override public void update(View view) { if (!getSubView().equals(view)) { getSubView().setVisibility(View.GONE); } } 
+1
source

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


All Articles