I'll write the code first and ask my question below
Below is my main class
public class Application {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
runApp();
}
});
}
public static void runApp() {
Model model = new Model();
View view = new View(model);
Controller controller = new Controller(view, model);
view.setLoginListener(controller);
}
}
Below is my another class
public class LoginFormEvent {
private String name;
private String password;
public LoginFormEvent(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Below is my controller class
public class Controller implements LoginListener {
private View view;
private Model model;
public Controller(View view, Model model) {
this.view = view;
this.model = model;
}
#Override
public void loginPerformed(LoginFormEvent event) {
System.out.println("Login event received: " + event.getName() + "; " + event.getPassword());
}
}
Below is my LoginListener interface
public interface LoginListener {
public void loginPerformed(LoginFormEvent event);
}
Lastly below is my view class which I have just deleted the JFrame code for simplicity.
public class View extends JFrame implements ActionListener {
private Model model;
private JButton okButton;
private JTextField nameField;
private JPasswordField passField;
private LoginListener loginListener;
#Override
public void actionPerformed(ActionEvent e) {
String password = new String(passField.getPassword());
String name = nameField.getText();
fireLoginEvent(new LoginFormEvent(name, password));
}
public void setLoginListener(LoginListener loginListener) {
this.loginListener = loginListener;
}
public void fireLoginEvent(LoginFormEvent event) {
if(loginListener != null) {
loginListener.loginPerformed(event);
}
}
}
It is a standard button coordinating code so you guys probably won't even need to read my code to answer my question.
So I know how to write this code and this is how I write it when I want a button to do call some action. But when I try to get my logic around it to understand 'why' it works, I get very confused.
so when I call view.setLoginListener(controller) I'm obviously expecting some kind of LoginFormEvent.
Then when I click the button, in the view class, new LoginFormEvent is constructed.
But then how is the constructed LoginFormEvent within the view class be set as the parameter of expected LoginFormEvent in controller class when there's not really any connection between the two classes except that I have defined view.setLoginListener(controller) in the Application class. This just makes setLoginListener of particular instance of view to expect some kind of LoginListener, meaning it doesn't really have to be the one that I set up in the view class upon a click of a button? But obviously it does have to be because that's how the code is run. but why?
You can see the flow as below
Lets start withApplication.java. lets see the method runApp(). It does below things.
Objects of View.java and Controller.java are created.
Controller.java implements LoginListener.java
view.setLoginListener(controller); // this sets the object of
Controller.java in the object of View.java, both these objects are
same as created in step-1.
Now lets move to View.java
It has a field private LoginListener loginListener; and method public void setLoginListener(LoginListener loginListener). This method sets the field loginListener As we see above in step 2 loginListener refers to the same object of Controller.java created in step 1 above.
Now lets move to public void actionPerformed(ActionEvent e) defined in View.java.
It calls fireLoginEvent(new LoginFormEvent(name, password)); See now Object of LoginFormEvent.java is created and it is passed as a parameter to the method fireLoginEvent(LoginFormEvent event).
Now moving to public void fireLoginEvent(LoginFormEvent event)
It has code : loginListener.loginPerformed(event);. From above we know loginListener refers to the one and only object of Controller.java
method public void loginPerformed(LoginFormEvent event) on that very object of Controller.java is called and same object of (again one and only one) LoginEvent.java is passed as parameter.
For such type of scenarios, I would recommend you to note the objects created of each type and connect the flow of calls. Hope above helps you understand the code.
Related
Recently I came across a problem which I was asked to design using appropriate design patterns. The proble statement is:
Implement a remote control of TV.
Any remote control we use, either at home/hotel or at a friend’s place,
we just pick up the TV remote control and start pressing Up and Down
or Forward and Back keys to change the channels.
Choose a suitable design pattern for implementation of this problem.
I am not able to figure out how to design this ask. This is what I came up with:
Place is an abstract class.
Home extends Place
Hotel extends Place
FriendPlace extends Place
TVRemote is a class
Place has a TVRemote
Keys is an interface
Keys has a method press()
UpKey, DownKey, ForwardKey, BackKey are classes implementing Keys
TVRemote has Keys
There could be more Keys in TVRemote
This is what I could think of but unable to incorporate a Design Pattern here. Any guidance?
A simplistic approach will be to create an interface
interface RemoteControl
{
public void up();
public vois down();
public void forward();
public void back();
}
and then create specific classes that will implement that interface for specific devices
e.g.
public class HomeRemote implements RemoteControl {
public void up(){
..
}
public vois down(){
..
}
public void forward(){
..
}
public void back(){
..
}
}
However
After our discussion - and after searching a little bit more, i am inclined to think now that Bridge pattern is what is asked for here.
Check this out - http://www.programcreek.com/2011/10/java-design-pattern-bridge/
There abstract class for remote control is used with basic implementation of (up,down,forward,back)
Then each specific TVRemote extends the abstract class to add more/and device specific functionality.
Also note that TVs are using common interface where (goUp(),goDown(),goForward(),goBack() and possibly on(),off()) functions are described.
Some observations:
different remote controls may have different number of buttons
different buttons execute different actions
remote control should be oblivious of the details how the action is executed
one should be able to reprogram remote control either by assigning different actions to buttons or by supporting different devices
The most straightforward pattern to use with this situation is Command. One could create specific Command implementations and then assign Commands to buttons:
public interface Command {
void Execute();
}
public class Button {
private readonly Command command;
public Button(Command command) {
this.command = command;
}
public void Press() {
this.command.Execute();
}
}
public class Remote {
public Button ButtonPlaceholder1 { get; set; }
public Button ButtonPlaceholder2 { get; set; }
public Button ButtonPlaceholder3 { get; set; }
public Button ButtonPlaceholder4 { get; set; }
}
So, what would be the benefit of having Button class? Well, let's say you want to introduce a slider button, which can be moved Up and Down. In this case, you will configure it with two Commands:
public class SliderButton {
public SliderButton(Command up, Command down) {
this.commandUp = up;
this.commandDown = down;
}
public void Up() {
this.commandUp.Execute();
}
public void Down() {
this.commandDown.Execute();
}
}
And interesting follow-up question on this interview would be, "How to implement a button that would cancel the action made by pressing previous button? (e.g. I was watching ESPN channel, but there was a break in between a match, so I switched to MTV, but I want to check once in a while whether break has ended, and if not, go back to MTV)
You should use command pattern here. Usually it has Invoker, Client, Command and Receiver. Here are the classes you may require.
Command
public interface ICommand {
void execute();
}
Invoker
public class RemoteControl {
Map<Key, ICommand> commandsByKey;
public RemoteControl() {
commandsByKey = new HashMap<>();
}
public void setCommand(Key key, ICommand command) {
commandsByKey.put(key, command);
}
public void press(Key key) throws Exception {
ICommand command = commandsByKey.get(key);
if(command == null)
throw new Exception("Invalid Key");
command.execute();
}
}
Receiver
public class TV {
private String brand;
public TV(String brand) {
this.brand = brand;
}
#Override
public String toString() {
return brand + " TV";
}
}
Client
public abstract class Place {
private TV tv;
private RemoteControl remoteControl;
public Place(TV tv) {
this.tv = tv;
this.remoteControl = new RemoteControl();
remoteControl.setCommand(Key.UP, new UpCommand(this.tv));
remoteControl.setCommand(Key.FORWARD, new ForwardCommand(this.tv));
remoteControl.setCommand(Key.DOWN, new DownCommand(this.tv));
remoteControl.setCommand(Key.BACK, new BackCommand(this.tv));
}
public TV getTv() {
return tv;
}
public RemoteControl getRemoteControl() {
return remoteControl;
}
}
public class Home extends Place {
public Home() {
super(new TV("Sony"));
}
}
public class Hotel extends Place {
public Hotel() {
super(new TV("LG"));
}
}
Concrete Commands
public class UpCommand implements ICommand {
private TV tv;
public UpCommand(TV tv) {
this.tv = tv;
}
#Override
public void execute() {
System.out.println("Up Command - " + tv);
}
}
public class DownCommand implements ICommand {
private TV tv;
public DownCommand(TV tv) {
this.tv = tv;
}
#Override
public void execute() {
System.out.println("Down Command - " + tv);
}
}
public class ForwardCommand implements ICommand {
private TV tv;
public ForwardCommand(TV tv) {
this.tv = tv;
}
#Override
public void execute() {
System.out.println("Forward Command - " + tv);
}
}
public class BackCommand implements ICommand {
private TV tv;
public BackCommand(TV tv) {
this.tv = tv;
}
#Override
public void execute() {
System.out.println("Back Command - " + tv);
}
}
Keys
public enum Key {
UP, DOWN, FORWARD, BACK
}
TEST
public class RemoteTest {
public static void main(String[] args) throws Exception {
Place home = new Home();
home.getRemoteControl().press(Key.UP);
home.getRemoteControl().press(Key.DOWN);
home.getRemoteControl().press(Key.BACK);
Hotel hotel = new Hotel();
hotel.getRemoteControl().press(Key.UP);
}
}
If you add any additional keys to the remote you don't need to touch any of the existing command or invoker. You just need to add it in the client. This adheres to Open Close principle. If you have different remote for each place then make it as constructor argument, so you no need to change any other classes.
I am having trouble figuring out why an EJB session bean is not working. The actual error message is an EJBException: NameNotFoundException, but that is not a very illuminating message.
I have traced it down to a exactly what line causes the problem, but have not figure out why. So, I wanted to create a session bean to keep track of the input values from a form.
A slimmed down version of the code is:
public class rrpInputField {
public boolean isRequired;
public int maxLength;
public String inputValue;
public String displayValue;
public String formatMask;
public rrpInputField() {
isRequired = false;
maxLength = 64;
inputValue = "";
displayValue = "";
formatMask = "";
}
}
I then created a interface dohicky...
#Local
public interface Test1 {
public void setAction(String action);
public String getAction();
public void setName(String name);
public String getName();
}
Then I created the test bean itself...
#Stateful
public class Test1Bean implements Test1 {
private String action;
private rrpInputField name;
#PostConstruct
public void initialize() {
action = "initalValue";
//name.currentValue = "TestValue";
#Override
public void setAction(String action){ this.action = action; }
#Override
public void getAction() { return this.action; }
#Override
public void setName(String name) { this.name.currentValue = name; }
#Override
public String getName() { return this.name.currentValue; }
}
In my test servlet I have
#EJB
private Test1 t1;
If I un-comment the one line in the bean initialize method in the bean definition I get the failure. So I know it has something to do with that.
//name.currentValue = "TestValue";
If I leave it commented out, as soon as I code t1.getName("New Value") in the servlet I'll get the same error.
If I leave it commented it out, then the bean works as anticipated - I can initialize, and use setAction and getAction just fine.
I am fairly sure the rrpInput class is correct, because I can code in the servlet:
rrpInputField f1 = new rrpInputField();
f1.currentValue = "TestValue";
I figure it must have something to do with my input field class, but I have had no luck figuring out what.
I really don't understand why, but I got it to work by adding a "new" thingie tin the initialize method of the Table1Bean.
#PostConstruct
public void initialize() {
action = "initialValue";
name = new rrpInputField();
name.currentVAlue = "TestValue;
}
If someone could explain why I had to do this, it would be illuminating.
I have a GUI that has 2 JTextFields- EmailLoginField and jPasswordField1. Ill just discuss the EmailLoginField and just duplicate what is recommended on jPasswordField1 too.
So heres some GUI code:
package p;
imports ...
public class EmailLoginGUI extends javax.swing.JFrame {
public EmailLoginGUI() {
initComponents();
}
private void initComponents() {
...
EmailLoginField = new javax.swing.JTextField();
}
...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
EmailMainGUI open = new EmailMainGUI();
open.setVisible(true);
This next code snippet is what I have tried to do to get the text from the JTextField EmailLoginField in EmailLoginGUI.java
public String getEmailLoginField(){
return EmailLoginField.getText();
}
public String getjPasswordField(){
return jPasswordField1.getText();
}
Here is the next part (not assuming the code immediately above is correct). This next code is an entirely different public class, which same package of course. Here is what I have tried it should look at the EmailLoginGUI class and get the JTextField content, eventually storing it as a String.
PLEASE NOTE: the final strings that contain the JTextField content MUST NOT be inside the SendEmail(EmailLoginGUI c1, EmailLoginGUI c2){. They should be just outside of it just inside public class SendEmail { this is so that they can be used by other code later.
package p;
imports ...
public class SendEmail {
JTextField userTF;
JPasswordField passPF;
SendEmail(EmailLoginGUI c1, EmailLoginGUI c2){
userTF.setText(c1.getEmailLoginField());
passPF.setText(c2.getjPasswordField());
}
public String user(){
return userTF.getText();
}
public String pass() {
return passPF.getText();
}
...
SendEmail(...) {
Properties props = new Properties();
...
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return new javax.mail.PasswordAuthentication(user(), pass()); //This is where the final strings need to go.
}
});
Hopefully what I am trying to do is clear:
Get the content from JTextField created in EmailLoginGUI.java. Get this into SendEmail.java. Its final type should be String and is 'just on the inside' of the public class SendEmail. I have had everything from NullPointerException to Cannot find symbol for hours! Think I've been attempting it for so long that I could benefit from some fresh eyes!
Help would be greatly appreciated.
In SendEmail class create Constructor which has an argument of user input
SendEmail(String userInput) {
//Your Code
}
In EmailLoginGUI create
String userInput = EmailLoginField.getText().toString();
SendEmail sendemail = new SendEmail(userInput);
This method works I have used it. Hope it helps.
I realised both the security risk and how a dialogue would be easier, however I don't have time to go back to change it really. I have already coded the listener too so that's not a problem. But yes that's what I want to do! Where am I going wrong?
Then you need to implement some kind of Observer Pattern.
Start by defining the expected operations that the login view might generate, for example, it's reasonable to expect that the user can either accept or cancel the view
public interface EmailLoginListener {
public void emailLoginWasAccepted(EmailLoginGUI gui);
public void emailLoginWasCanceled(EmailLoginGUI gui);
}
Update the view to provide support for the listener
public class EmailLoginGUI extends javax.swing.JFrame {
private List<EmailLoginListener> listeners;
public EmailLoginGUI() {
initComponents();
listeners = new ArrayList<>(25);
}
//...
public void addEmailLoginListener(EmailLoginListener listener) {
listeners.add(listener);
}
public void removeEmailLoginListener(EmailLoginListener listener) {
listeners.add(listener);
}
protected void fireLoginWasAccepted() {
for (EmailLoginListener listener : listeners) {
listener.emailLoginWasAccepted(this);
}
}
protected void fireLoginWasCanceled() {
for (EmailLoginListener listener : listeners) {
listener.emailLoginWasCanceled(this);
}
}
}
In your action handlers for your buttons on the EmailLoginGUI view, trigger the required event...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
fireLoginWasAccepted();
}
Remember, you should also do this for the cancel operation if you have one.
Now, when you create an instance of EmailLoginGUI, make sure you also register a EmailLoginListener with it
EmailLoginGUI loginView = new EmailLoginGUI();
loginView.addEmailLoginListener(new EmailLoginListener() {
#Override
public void emailLoginWasAccepted(EmailLoginGUI gui) {
gui.dispose();
String email = gui.getEmailLoginField();
String password = gui.getjPasswordField();
EmailMainGUI open = new EmailMainGUI();
open.setCredentials(email, password);
//...
open.setVisible(true);
}
#Override
public void emailLoginWasCanceled(EmailLoginGUI gui) {
// Exit the program?
gui.dispose();
}
});
//...
loginView.setVisible(true);
This will require you to either change the constructor of EmailMainGUI to accept the email and password or a method to pass that information to the class (as I've demonstrated above)
Finally change SendEmail to accept String values instead of your gui components
public class SendEmail {
String email;
String password;
SendEmail(String email, String password) {
this.email = email;
this.password = password;
}
public String user() {
return email;
}
public String pass() {
return password;
}
}
I want to use java interface in a way that i will make a call defining interface in my other class like 'private SoapURL soapURL;' and than i can access any class's method for example : i want to use login:-
private SoapURL soapURL;
SoapUrl = LoginSoap ();
String nameSpace = soapURL.getMethodName();
String url = soapURL.getUrl();
Is there any way to do something like this. I am sorry i am not very good with Object Oriented principles but if there is a solution for my problem i would like to know it. Thanks in advance.
public interface SoapURL {
public String getNameSpace();
public String getUrl();
public String getSoapAction();
public String getMethodName();
public String getTag();
}
LoginSoap class
public class LoginSoap implements SoapURL {
#Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
#Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
#Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserControl";
}
#Override
public String getMethodName() {
return "UserControl";
}
#Override
public String getTag() {
return "Login Activity";
}
}
SignUpSoap class
public class SignUpSoap implements SoapURL {
#Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
#Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
#Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserRegister";
}
#Override
public String getMethodName() {
return "UserRegister";
}
#Override
public String getTag() {
return "SignUp Activity";
}
}
ResetPasswordSoap class
public class ResetPasswordSoap implements SoapURL {
#Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
#Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
#Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserPasswordReset";
}
#Override
public String getMethodName() {
return "UserPasswordReset";
}
#Override
public String getTag() {
return "Forget Password Activity";
}
}
Your implementation looks correct. To make use of it, you can do this in main:
SoapURL reset = new ResetPasswordSoap();
System.out.println(reset.getUrl());
This is a method of minimizing coupling in large systems. And reduces dependency between objects by making use of a common interface for groups of objects that work together. You might be new at Object oriented principles, but you are one step ahead of the game already
To pass it to a function, you do:
public JPanel resetPass(SoapURL reset) {
...
}
// In main:
JPanel resetPassPanel = resetPass(reset);
Just do, for example:
SoapURL example = new LoginSoap();
String a = example.getTag();
a should be equal to "Login Activity"
The main use of Interface is polymorphism, or the ability to perform the same
operation on a number of different objects,
which is exactly what you wanted in your scenario
Your approach is absolutely fine , just a modification needed
private SoapURL soapURL;
//SoapUrl = LoginSoap (); // This line should be replaced with the Below line
soapURL=new LoginSoap();
String nameSpace = soapURL.getMethodName();
String url = soapURL.getUrl();
Since LoginSoap, SignUpSoap,ResetPasswordSoap classes are implemented classes of SoapURL Interface , thus reference variable of SoapURL can store Object of any of these child classes
soapURL=new LoginSoap();//soapURL.someMethod will call method of LoginSoapClass
soapURL=new SignUpSoap();// will call method of SignUpSoap class
soapURL=new ResetPasswordSoap();
I cannot seem to find an answer anywhere to my question. Is there any event listener which can detect the changing of a boolean or other variable and then act on it. Or is it possible to create a custom event listener to detect this?
Please I cannot seem to find a solution to this anywhere and I found this website explaining how to create custom events
Use PropertyChangeSupport. You wont have to implement as much and it is thread safe.
public class MyClassWithText {
protected PropertyChangeSupport propertyChangeSupport;
private String text;
public MyClassWithText () {
propertyChangeSupport = new PropertyChangeSupport(this);
}
public void setText(String text) {
String oldText = this.text;
this.text = text;
propertyChangeSupport.firePropertyChange("MyTextProperty",oldText, text);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
}
public class MyTextListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals("MyTextProperty")) {
System.out.println(event.getNewValue().toString());
}
}
}
public class MyTextTest {
public static void main(String[] args) {
MyClassWithText interestingText = new MyClassWithText();
MyTextListener listener = new MyTextListener();
interestingText.addPropertyChangeListener(listener);
interestingText.setText("FRIST!");
interestingText.setText("it's more like when you take a car, and you...");
}
}
Just like you need to create an event listener, you will also need to create the event firer -- since there is nothing automatic that will do this for you. I've provided sample code that shows you how to implement such a firer.
This test implementation isn't perfect. It only includes a way to add listeners. You may wish to include a way to remove listeners who are no longer interested in receiving events. Also note that this class is not thread-safe.
import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue;
/**
* This class uses the EventQueue to process its events, but you should only
* really do this if the changes you make have an impact on part of a GUI
* eg. adding a button to a JFrame.
*
* Otherwise, you should create your own event dispatch thread that can handle
* change events
*/
public class BooleanChangeTest implements BooleanChangeDispatcher {
public static void main(String[] args) {
BooleanChangeListener listener = new BooleanChangeListener() {
#Override
public void stateChanged(BooleanChangeEvent event) {
System.out.println("Detected change to: "
+ event.getDispatcher().getFlag()
+ " -- event: " + event);
}
};
BooleanChangeTest test = new BooleanChangeTest(false);
test.addBooleanChangeListener(listener);
test.setFlag(false); // no change, no event dispatch
test.setFlag(true); // changed to true -- event dispatched
}
private boolean flag;
private List<BooleanChangeListener> listeners;
public BooleanChangeTest(boolean initialFlagState) {
flag = initialFlagState;
listeners = new ArrayList<BooleanChangeListener>();
}
#Override
public void addBooleanChangeListener(BooleanChangeListener listener) {
listeners.add(listener);
}
#Override
public void setFlag(boolean flag) {
if (this.flag != flag) {
this.flag = flag;
dispatchEvent();
}
}
#Override
public boolean getFlag() {
return flag;
}
private void dispatchEvent() {
final BooleanChangeEvent event = new BooleanChangeEvent(this);
for (BooleanChangeListener l : listeners) {
dispatchRunnableOnEventQueue(l, event);
}
}
private void dispatchRunnableOnEventQueue(
final BooleanChangeListener listener,
final BooleanChangeEvent event) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
listener.stateChanged(event);
}
});
}
}
interface BooleanChangeDispatcher {
public void addBooleanChangeListener(BooleanChangeListener listener);
public boolean getFlag();
public void setFlag(boolean flag);
}
/**
* Listener interface for classes interested in knowing about a boolean
* flag change.
*/
interface BooleanChangeListener extends EventListener {
public void stateChanged(BooleanChangeEvent event);
}
/**
* This class lets the listener know when the change occured and what
* object was changed.
*/
class BooleanChangeEvent extends EventObject {
private final BooleanChangeDispatcher dispatcher;
public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
super(dispatcher);
this.dispatcher = dispatcher;
}
// type safe way to get source (as opposed to getSource of EventObject
public BooleanChangeDispatcher getDispatcher() {
return dispatcher;
}
}
you can also try to implement an Observer.
First create the observable object:
import java.util.Observable;
public class StringObservable extends Observable {
private String name;
public StringObservable(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}
}
Then the observer:
import java.util.Observable;
import java.util.Observer;
public class NameObserver implements Observer {
private String name;
public NameObserver() {
name = null;
}
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
name = (String) arg;
System.out.println("NameObserver: Name changed to " + name);
} else {
System.out.println("NameObserver: Some other change to subject!");
}
}
}
And in your main (or wherever else):
public class TestObservers {
public static void main(String args[]) {
// Create the Subject and Observers.
StringObservable s = new StringObservable("Test");
NameObserver nameObs = new NameObserver();
// Add the Observer
s.addObserver(nameObs);
// Make changes to the Subject.
s.setName("Test1");
s.setName("Test2");
}
}
Mostly found here
Very late to answer, but this is a problem that can be solved with Observer/Observable. Example
The boolean you are setting should be allowed to do only through a setter method like:
public void setFlag(boolean flag){
//Method code goes here
}
Now in now set method, you can decide based on what value comes in, what event needs to be fired. I am explaining in simple terms without introducing complex terms so you can understand better, so code snippet would look like:
public void setFlag(boolean flag){
//if flag is TRUE do something
//If flag is FALSE then do something
//And finally do what you needed to do with flag
}
Ask questions if you need more info
you create a listener when you want to listen for I/O changes. mostly on graphics.
the answer to your question is to keep state of the running program, then check if variables change from the state inside the infinite loop of your program.
You can use AOP for that, perhaps AspectJ? Check a few examples here (if you use Eclipse, then using AspectJ is really simple with their plugin).
For you, you would have a pointcut similar to the one used in the SampleAspect, but one that will only be used when someone makes a new SET to a boolean variable (this doesn't mean that the value has changed, just that someone loaded a value to the variable).