Passing Multiple objects To Each other - java

This is a little weird question, I have a GUI class that in the constructor initiates a Logic class that takes care of the processing of the Processing or Logistics in the App then their is a Handler class that contains a bunch of ActionListners KeyListeners that are attached to UI components in the GUI class
In Constructor of both the Logic and Handler class I take in as parameter the GUI class to be able to manipulate the GUI components created in the GUI class from both the Logic and Handler classes
My problem is that The Handler makes use of the Logic class and vise versa (the Logic class uses the Handler class) and thats not really possible with the method I described above, one is instance before the other, one will be null when attempting to use the other.
Example:
public class GUI()
{
this.handler = new Handler(this);
this.logic = new Logic(this);
}
If handler tries to use something in logic then null would be returned.
One way to fix this is to a setter for the handler to take the logic and vise versa but that doesn't seem like the answer to this.

simple:
public class GUI()
{
this.handler = new Handler(this);
this.logic = new Logic(this);
handler.setLogic(logic);
logic.setHandler(handler);
}

I think it is possible just to expose the Handler and Logic in GUI, and let the public access it. By doing so, as your Handler and Logic already have reference to GUI, they can indirectly get access to each other:
class Gui {
private Handler handler;
private Logic logic;
public Handler getHandler() {
return this.handler;
}
public Logic getLogic() {
return this.logic;
}
}
class Handler {
private Gui gui;
public Handler(Gui gui) {
this.gui = gui;
}
public void doSomething() {
// access logic
this.gui.getLogic().doSomeLogic();
}
}
Regarding to "elegance", I don't think the original design of (imho) messy dependencies between component is elegant at all :) So, instead of focusing making such things look "elegant", do some rethinking and possibly you will find everything become much more elegant automatically. :)

Right before your first usage of handler and logic you could put this code snippet
if(handler == null)
this.handler = new Handler(this);
if(logic == null)
this.logic = new Logic(this);

Related

Android Redirection (delegates pointers)

I would like to call different code (callbacks) from within a background thread loop and use that background thread to perform the work. It would be similar to delegates in C#.
public class test {
private boolean keepRunning;
private boolean messageReady;
private MyClass myClass;
void LongBackgroundWork(){
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (keepRunning) {
if (messageReady){
myClass.callback(); // call different methods here
// to be decided at runtime and run on this worker thread
}
}
}
});
thread.start();
}
}
I want to use the background thread not the UI thread. I want to set a callback from within myClass to choose what code is called. It's easy in C# how to do it Java.
I don't have much experience in Java and don't understand what mechanism to use. Should I be using a handler? Can a handler run code on a background thread?
I'd wager you want to have a pattern where an event or some occurence happens and you need to initiate a code block somewhere.
A pattern that could help you is perhaps an Observer Wiki and firing off to the event. You can also check out this SO question here if you'd like: Delegate vs Callback in Java
In your case, I think you'd want to have someone handle the responsibility of what you have to do when a message is ready. So what you're looking for is someone to perform the action, once the event is read (message ready).
Take for example Class Foo is your container of listeners, or also called an Observer that will be notified of any events. You can have a list of callbacks here to some object that is responsible for your logic to do what you need to do next.
Then you would have an Observable object or a class that would implement some logic when notified. You could then have various class objects perform the necessary logic by implementing the callback function required.
Example:
// Observer
public class Foo {
// List of objects that implement Callbacks interface
private List<Callbacks> mList;
public Foo() {
// Initialize here
}
public void addListener(Callbacks cb) {
mList.add(cb);
}
public void notifyListeners() {
for ( Callback cb : mList) {
cb.onCallback();
}
}
// Public interface to be implemented by users
public interface Callback {
void onCallback();
}
}
Then just have a class implement this object and you can pass it along if you'd like.
// Bar implements Foo.Callback interface
public class Bar implements Foo.Callback {
public class Bar() {}
#Override
public void onCallback() {
// Perform logic here
}
}
Finally in your code, you'd just create the Foo object, add a listener, and notify them when it's time to fire your event.
if i understood you properly,you cant do this on UI thread, basically when android see Thread like this it will expect that it's a long operation however you can call it by AsyncTask or Handler
you can make something like this
private class MyAsyncTask extends AsyncTask<Void,Void,Void>{
protected Void doInBackground() {
MyClass myClass=new MyClass();
myClass.LongBackgroundWork();
}
return totalSize;
}
}
this is how yo can call your thread otherwise you have to use Handler instead
Handler handler=new Handler();
handler.post(new Runnable(){
MyClass myClass=new MyClass();
myClass.LongBackgroundWork();
})

Java enum that registers as listener on creation

There are two good (as considered by most) java practices that i try to combine and fail.
Never leak this in a constructor.
Use enum instead of singleton pattern.
So, I want a singleton that as soon as created, listens for some event. Here's an example. First, the event listener interface:
public interface EventListener {
void doSomething();
}
Then, the event producer:
public class EventProducer implements Runnable{
private EventListener listener;
public EventProducer(EventListener listener) {
if (listener == null) {
throw new NullPointerException("Listener should not be null.");
}
this.listener = listener;
}
#Override
public void run() {
listener.doSomething(); //This may run before the listener is initialized.
do {
long startTime = System.currentTimeMillis();
long currentTime;
do {
currentTime = System.currentTimeMillis();
} while ((currentTime - startTime) < 1000);
listener.doSomething();
} while (!Thread.currentThread().isInterrupted());
listener = null; //Release the reference so the listener may be GCed
}
}
Then, the enum (as the 2nd listed java practice suggests):
public enum ListenerEnum implements EventListener{
INSTANCE;
private int counter;
private final ExecutorService exec;
private ListenerEnum() {
EventProducer ep = new EventProducer(this); //Automatically unregisters when the producer is done.
counter = 0;
exec = Executors.newSingleThreadExecutor();
exec.submit(ep);
}
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
exec.shutdownNow();
}
}
}
And finally, something to get things started:
public class TestRunner {
public static void main(String[] args) {
ListenerEnum.INSTANCE.doSomething();
}
}
The problem lies in the first line of the ListenerEnum constructor, as we are leaking this, thus not conforming to the 1st listed java practice. This is why our event producer can call a listener's method before the listener is constructed.
How do I deal with this? Normally I would use a Builder pattern, but how is that possible with an enum?
EDIT:
For those that it matters, the event producer in my program actually extends a BroadcastReceiver, so my enum cannot be the event producer, they have to be separate. The producer is created in the constructor of the enum (as the example) and is registered programmatically later on. So I don't actually have a problem leaking this. Nevertheless, I'd like to know if I could avoid it.
EDIT 2:
Ok, since there are suggestions to solve my problem, i'd like to clarify some things. First of all, most suggestions are workarounds. They suggest doing the same thing in a completely different way. I appreciate the suggestions, and probably will accept one as answer and implement it. But the real question should be "How do i implement a Builder pattern with an enum?" The answer i already know and people suggest is "You don't, do it some other way.". Is there anyone who can post something like "You do! You do it this way."?
I was asked to give code close to my actual use case. Modify the following:
public enum ListenerEnum implements EventListener{
INSTANCE;
private EventProducer ep;
private int counter;
private ExecutorService exec;
private ListenerEnum() {
ep = new EventProducer(this); //Automatically unregisters when the producer is done.
counter = 0;
}
public void startGettingEvents() {
exec = Executors.newSingleThreadExecutor();
exec.submit(ep);
}
public void stopGettingEvents() {
exec.shutdownNow();
}
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
stopGettingEvents();
}
}
}
As well as this:
public class TestRunner {
public static void main(String[] args) {
ListenerEnum.INSTANCE.startGettingEvents();
}
}
Now all i have to do to solve my problem is move the EventsProducer creation to the startGettingEvents() method. That's it. But that is also a workaround. What i'd like to know is: In general, how do you avoid leaking this in the constructor of a listener enum since you can't use the Builder pattern? Or can you actually someway use the Builder pattern with an enum? Is it done only by workarounds in a case by case basis? Or is there a general way to deal with this that i don't know of?
Just create a static initialization block:
public enum ListenerEnum implements EventListener{
INSTANCE;
private int counter;
private static final ExecutorService exec; //this looks strange. I'd move this service out of enum.
private static final EventProducer ep;
static{
exec = Executors.newSingleThreadExecutor();
ep = new EventProducer(INSTANCE); //Automatically unregisters when the producer is done.
exec.submit(ep);
}
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
exec.shutdownNow();
}
}
}
As long as enum values are final and static they are initialized before the static initialization block. If you decompile the enum you'll see a single initialization block:
static{
INSTANCE = new ListenerEnum();
exec.submit(INSTANCE.ep);
}
First, consider why this shouldn’t escape:
You loose the final field safe publication guaranty in case of an improper publication of the instance
Even with a safe publication there are inconsistencies regarding all action not performed within the constructor at the time of the leakage
You will let escape an incomplete instance in case of subclasses as the subclass’ constructor hasn’t been called so far
That doesn’t apply to you in this narrow case. Submitting to an Executor is not an improper publication and enum’s can’t escape in any other way besides the one you have implemented yourself in the constructor. And its the last thing in the constructor whereas enums can’t have subclasses.
Now that you have edited your question, it makes much lesser sense. The constructor
private ListenerEnum() {
ep = new EventProducer(this);
counter = 0;
}
is not a “leaking this” as long as ep is not a static variable and the constructor of EventProducer does not let leak its this as well. This is important as programmers must be able to create circular object graphs without fearing sudden inconsistencies.
But it is still nothing you should take too easy. As said, it relies on the behavior of the EventProducer regarding leakage and regarding that EventProducer must not call back into ListenerEnum which could break things without being a “leaking this”, technically. After all, you can create code that breaks without breaking thread safety.
So it’s code for which you can’t see the correctness when looking at it as you need knowledge about another class.
  There are use cases where passing this to another object is considered safe because of well-known behavior, e.g. weakThis=new WeakReference(this); is a real-life example. However, passing this to something called EventProducer is likely to let alarm bells ringing for every reader which you should avoid even if you know for sure that it’s false-alarm.
However, the big design smell lies in the use of the Singleton pattern in itself. After all, every instance you create is unique in the first place. What is special about the Singleton pattern is that it provides global public access to that instance. Is that really what you want? Did you consider that by using the Singleton pattern, everyone inside the entire application could register that listener again?
The fact that your class is a singleton (whether enum-based or otherwise) is unrelated to your problem. Your problem is simply how to register a listener within the constructor of an object. And the answer is: it's not possible, safely.
I would recommend you do two things:
Ensure your listener doesn't miss out on events by having a queue that it polls for work. This way, if it temporarily isn't listening, the work just queues up. In fact, this means it doesn't really need to be a listener in the traditional sense. It just needs to poll on a queue.
Register the class as a listener using a separate method, as discussed in the comments.
I would give some thought to avoiding a singleton. It doesn't offer many advantages (asides from the minor benefit of being able to call SomeClass.INSTANCE from anywhere). The downsides are most strongly felt during testing, where you find it much harder to mock the class when you wish to test without actually sending things over the network.
Here's a concrete example of why leaking this is dangerous in your case. Your constructor passes this before setting counter to zero:
private ListenerEnum() {
ep = new EventProducer(this);
counter = 0;
}
Now, as soon as this escapes, your event producer might invoke doSomething() 5 times before the constructor completes:
#Override
public void doSomething() {
System.out.println("Did something.");
counter++;
if (counter >= 5) {
exec.shutdownNow();
}
}
The sixth call to this method ought to fail right? Except that your constructor now finishes and sets counter = 0;. Thus allowing the producer to call doSomething() 5 more times.
Note: it doesn't matter if you reorder those lines as the constructor may not be executed in the order it appears in your code.

Double observer in java?

I have a problem with Observer pattern.
First, I have a HttpHelper class to get data from server, I used it as Observerable.
public class HttpHelper extends Observable,Runnable{
public void run(){
//do long task to get data
String result = getData();
setChanged();
notifyObservers(result);
}
}
The DataManager class get data from HttpHerlper when completed, then do some business task.
public class DataManager implements Observer {
public void doTask(){
HttpHelper helper = new HttpHelper();
helper.addObserver(this);
Thread thread = new Thread(helper);
thread.start();
}
public void update(Observable obj, Object data) {
if (data instanceof String) {
// do some stuff with this data
// Then I want to notify the result to the view
Model model = doSomething(data);
notify(model)
}
}
}
Finaaly, View class will update data when DataManager complete task.
public class View{
private void getData(){
DataManager manager = new DataManager()
manager.doTask();
}
public void update(Observable obj, Object data) {
}
}
Should I use Observer again? And how can I do that?
P/s: for some reason, HttpHelper and DataManager must be separated.
Update: Here is the class structure
https://www.dropbox.com/s/givn6vzvqr4cgye/bkd.png
IMO, the relationship between HttpHelper and DataManager doesn't need an observer pattern. It seems to be just a callback to notify the manager that the processing is done. Observers are better suited for dispatching events to multiple, different listeners via a common interface, not to a single listener. Having said that, what you have will work. Check this article on implementing callbacks if you want to follow my advice
Now, for the relationship between the manager and the view i do agree that you should use an observer pattern, this will allow you to create different views that react differently to the same events. This means that it's DataManager that should extend Observable, and every view listening it should implement Observer
Finally, i have to say that if you plan on having different types of events, the JDK observable and observer (java.util) mechanism is not very clean. My biggest criticism is that the second argument of update is an Object, so you end up with a huge list of if else where you need to check instanceof like in your example, which in general is not good practice. An alternative is to use the event notification mechanism from the UI classes (like EventObject and EventListener) , they are part of the UI classes but are really more generic than just UIs. see this other question
Oh and if you can, try to avoid cascading events. It makes code hard to read and debug. Maybe the view could observe directly the HttpHelper??
I think you can make the View an Observable but that chain of Observation may make your code complex.
The immediate solution came to me is:
Make an Observer controller
class Controller implements Observer{
DataManager dm;
View v;
void update(...){
Data d = dm.getData();
v.loadData(d);
}
}
and make your Controller observe HttpHelper.

how to implement a callback in runnable to update other swing class

I have a thread like this
public class SMS {
class Read implements Runnable {
Read(){
Thread th = new Thread(this);
th.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true){
Variant SMSAPIReturnValue = SMSAPIJava.invoke("ReadSMS");
if (SMSAPIReturnValue.getBoolean()){
String InNumber = SMSAPIJava.getPropertyAsString("MN");
String InMessage = SMSAPIJava.getPropertyAsString("MSG");
}
}
}
}
}
How do I update the message to another GUI class in the same package(I understand how to put nested class to another package ....). Should I implement a callback function in SMS class? But how? Or should I pass in the Jlabel into the class?
If I read you correctly--if you want the other class to hear an event generated in this class, you should have that class add itself as a listener to this class.
Just pass the GUI components you want to update into SMS class, don't worry much about memory because it will be passed by reference, another choice is to have a singleton view class and any component you want to edit or update should have a getter function in the view class.
View.getSingleton().getJLabel1().setText(InNumber);

How can I place #Action methods in a separate class from a Swing component?

When developing Swing applications, I've typically defined a delegate interface for each UI component for action callbacks. For example, if there is a class, MyDialog, which contains a button, MyButton, then the ActionListener for MyButton will call MyDialog.Delegate.OnMyButtonClick(Event e). The UI component then becomes "dumb" and requires a controller to handle events as well as update the component itself.
I thought that by using the Swing Application Framework's #Actions, I could get around creating delegate interfaces and implementations by defining #Action methods in implementation classes, letting the ApplicationContext figure out what to call. Apparently, that is not the case, as I don't see any clear way of adding those classes into the ApplicationContext, nor do I see any examples out there of doing such a thing.
Has anyone managed to use SAF in this manner so that there is a clean separation between UI and UI action code?
I've discovered a good way to keep the UI separate from the behavior using #Actions.
First, create a UI Component, say a JPanel with a button and then give it a public method that can be used to set the action of the Button:
class CustomJPanel extends JPanel {
private JButton myButton;
public CustomJPanel() {
initializeComponents();
}
public void initializeComponents() {
myButton = new JButton();
}
public void setButtonAction(javax.swing.Action action)
{
myButton.setAction(action);
}
}
Next, create an Action class that will provide the logic for that button:
class CustomJPanelActions {
#Action
public void doSomething()
{
JOptionPane.showMessageDialog(null,"You pressed me!");
}
}
Finally, setup the application controller and during setup, assign the appropriate action to the appropriate UI:
class MyApp extends SingleFrameApplication {
private JFrame mainFrame;
private JLabel label;
#Override
protected void startup() {
getMainFrame().setTitle("BasicSingleFrameApp");
CustomJPanel panel = new CustomJPanel();
panel.setButtonAction(getContext().getActionMap(new CustomJPanelActions()).get("doSomething");
show(panel);
}
public static void main(String[] args) {
Application.launch(BasicFrameworkApp.class, args);
}
}
In this way, the UI is logically separated from the control (i.e. Action) and can be tested on its own. The controller can make any decisions it needs to in order to determine what Action set to use and which specific action to assign to the UI controls. That is, one can create a Test Action Set and a Live Action Set, etc.
This method of using SAF has worked rather well for me.
The SAF javadoc has some information on how to do this sort of thing in the doc for ActionManager#getActionMap

Categories