Blackberry design pattern question: - java

I'm implementing a class that is responsible for all my HTTP requests from the Blackberry. I have around 10 or so screens that use this class to query a web service and get data from it. What would be the standard pattern to use in this case?
Currently I have it setup as follows -
public class NetworkAccessClass
{
public NetworkAccessClass(String url, String methodName, Vector paramNames, Vector paramValues, MainScreen screen) {
// perform inits
}
public void run() {
// Get Data
if(screen.instanceOf(LoginScreen)) {
((LoginScreen) screen).requestSucceded(responseData);
}
// So on for all 10 screens.
catch() {
((LoginScreen) screen).requestFailed(errorCode);
// So on for all 10 screens.
}
}
}
It works, but doesn't look right, and if a single screen has multiple types network requests, I'm being forced to add a flag to keep track of which function it's supposed to call back.
Is there a better way to do this?
Thanks,
Teja.

Use a callback interface, e.g. ResponseHandler:
public class NetworkAccessClass
{
public interface ResponseHandler {
void requestSucceeded(ResponseData responseData);
void requestFailed(ErrorCode errorCode);
}
public NetworkAccessClass(
String url,
String methodName,
Vector paramNames,
Vector paramValues,
ResponseHandler responseHandler) {
// perform inits
}
public void run() {
// Get Data
try {
...
responseHandler.requestSuceeded(responseData);
catch() {
responseHandler.requestFailed(errorCode);
}
}
}
This hopefully decouples your NetworkAccessClass from knowing about all the screens. Then either your screens implement NetworkAccessClass.ResponseHandler or they pass an adapter handler (anonymous inner class) to call the proper methods on the screen, e.g.
class LoginScreen {
...
new NetworkAccessClass(url, methodName, paramNames, paramValues,
new ResponseHandler() {
#Override
void requestSucceeded(ResponseData responseData) {
LoginScreen.this.handleLoginSuccess(responseData);
}
#Override
void requestFailed(ErrorCode errorCode) {
LoginScreen.this.handleLoginFailure(errorCode);
}
}
...
}

You could use a listener, which is a simple interface the network class would call back whenever something interesting happens :
public interface NetworkListener {
void requestSucceeded(byte[] responseData);
void requestFailed(int errorCode);
}
public class NetworkAccess {
// ...
public void run() {
// Get Data
if (successful) {
fireSucess(responseData);
}
catch(SomeException e) {
fireFailure(errorCode);
}
}
public void addNetworkListener(NetworkListener listener) {
// add listener to list of listeners
}
private void fireSuccess(byte[] responseData) {
for (NetworkListener l : listeners) {
l.requestSucceeded(responseData);
}
}
// ...
}
public class LoginScreen {
private void foo() {
NetworkAccess access = new NetworkAccess(...);
access.addNetworkListener(new NetworkListener() {
public void requestSucceeded(byte[] responseData) {
// do what you want
}
public void requestFailed(int errorCode) {
// do what you want
}
});
}
}
This is known as the Observable/observer pattern. The observable notifies its observers when something happens, but without having to know their exact type. The listsner class decouples the two parties.

Related

Multi-Level Enum with Methods in Java

I have 2 enums and 2 interfaces that I am trying to create in a specific way. The goal is to form a hierarchy where I can declare a list of methods that belong to one enum and a differnent list of values that belong to the combination of both enums.
For example: the methods declared within LevelOneOperations should belong to LevelOne only. Then methods declared witin LevelTwoOperations should belong to the combination of both together like A.1, A.2, A.3, etc.
public enum LevelOne implements LevelOneOperations {
A {
public boolean isValid(Request obj){ // logic }
public void prepare(Request obj){ // logic }
},
B {
public boolean isValid(Request obj){ // logic }
public void prepare(Request obj){ // logic }
} ...
}
public enum LevelTwo implements LevelTwoOperations {
1 {
public void process(LevelOne lev1, Request obj){
switch(lev1){
case A: // do something
case B: // do something else
case C: // do something else
case D: // do the last thing
}
}
},
2 {
public void process(LevelOne lev1, Request obj){ // logic }
} ...
}
public interface LevelOneOperations {
public boolean isValid(Request obj);
public void prepare(Request obj);
}
public interface LevelTwoOperations {
public void process(LevelOne lev1, Request obj);
}
public class myService {
public void runProcess(Request obj){
LevelOne l1 = LevelOne.valueOf(obj.getLevel1());
LevelTwo l2 = LevelTwo.valueOf(obj.getLevel2());
if(l1.isValid()){
l1.prepare();
l2.process(l1, obj);
}
}
}
Is there a way I can create an enum hierarchy so that I don't need to use switch statements to control the flow of the application. I want to call the process like: LevelOne.LevelTwo.process(obj);
I need methods that apply to LevelOne for all types and some methods that apply to LevelOne.LevelTwo together so that I have a grouped enum like : A.1, A.2, A.3, B.1, B.2, B.3, C.1, C.2, C.3, D.1, D.2, D.3, etc. I am also trying to make it easy to expand upon in the future because these lists are only subsets of what we are expecting for this project.
Tomorrow if I want to add a new LevelOne like E or a new LevelTwo 4 then it shouldn't require a lot of rework to introduce and support a new constant like that. The internal business logic between each element is different. Even between sub levels like: A.1 and A.2 will be different because both enumerators are taken into consideration and effect the output of the process.
The only way that I can think of to implement any thing like this is through switch/case statements. Can you please let me know if there is another way that I can achieve this?
I don't want separate classes for each variation because it will be a lot of different service classes and this is for only one part of my application. Currently I would have 5 elements in my first enumerator and 2 elements in my second enumerator for a total of 10 combinations.
You can use the Visitor pattern for this.
If you add a new enum to either of them, you're forced to implement all the new methods before the code will compile, unlike with a switch where you won't get compilation error if you miss one.
interface VerbAction {
void run();
void walk();
void jump();
}
enum Verb {
Run { #Override void perform(VerbAction action) { action.run(); } },
Walk { #Override void perform(VerbAction action) { action.walk(); } },
Jump { #Override void perform(VerbAction action) { action.jump(); } };
abstract void perform(VerbAction action);
}
enum Noun {
Dog {
#Override
void perform(Verb verb) {
verb.perform(new VerbAction() {
#Override
public void run() {
// Running dog
}
#Override
public void walk() {
// Walking dog
}
#Override
public void jump() {
// Jumping dog
}
});
}
},
Cat {
#Override
void perform(Verb verb) {
verb.perform(new VerbAction() {
#Override
public void run() {
// Running cat
}
#Override
public void walk() {
// Walking cat
}
#Override
public void jump() {
// Jumping cat
}
});
}
},
Pony {
#Override
void perform(Verb verb) {
verb.perform(new VerbAction() {
#Override
public void run() {
// Running pony
}
#Override
public void walk() {
// Walking pony
}
#Override
public void jump() {
// Jumping pony
}
});
}
};
abstract void perform(Verb verb);
}

Is this Java a good approximation of how #UIApplicationMain works in Swift?

I trying to understand the automagic of #UIApplicationMain and how to visualize the start of an an iOS app in terms of Java:
public class UIApplication extends UIResponder implements Runnable {
final UIApplicationDelegate appDel;
public UIApplication(UIApplicationDelegate appDel) {
this.appDel = appDel;
}
public static void main(String[] args) {
try {
UIApplication app = new UIApplication(new AppDelegate());
handThisReferenceToOperatingSystem(app);
iOSdoesSomethingLikeThis(new Thread(app).start());
} catch(Exception e) { e.printStackTrace(); }
}
public void run() {
// chill-out and wait for iOS to invoke methods in UIResponder class.
// The UIResponder methods invoke my custom methods in AppDelegate.
}
public static class AppDelegate implements UIApplicationDelegate {
public void application(Object UIApplication) { // app specific behaviour
}
public void applicationWillResignActive(Object UIApplication) { // app specific behaviour
}
public void applicationDidEnterBackground(Object UIApplication) { // app specific behaviour
}
public void applicationWillEnterForeground(Object UIApplication) { // app specific behaviour
}
public void applicationDidBecomeActive(Object UIApplication) { // app specific behaviour
}
public void applicationWillTerminate(Object UIApplication) { // app specific behaviour
}
// maybe more methods from the UIApplicationDelegate
}
public interface UIApplicationDelegate {
void application(Object UIApplication);
void applicationWillResignActive(Object UIApplication);
void applicationDidEnterBackground(Object UIApplication);
void applicationWillEnterForeground(Object UIApplication);
void applicationDidBecomeActive(Object UIApplication);
void applicationWillTerminate(Object UIApplication);
// maybe some more methods ....
}
}
public class UIResponder {
void fingerSwipe() { // default implementation
}
void verticalMotion() { // default implementation
}
// more methods iOS might invoke
}
So basically, applying the #UIApplicationMain attribute to the AppDelegate class makes all the other code go away, right?
Check out this answer: https://stackoverflow.com/a/24516329/335974
The gist is that it generates the main.m file found in Objective-C projects:
int main(int argc, char *argv[]) {
#autoreleasepool {
NSString *appDelegateClassName = #"AppDelegate";
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
}
So your Java code looks like in the ballpark of what happens.

How to properly convert Listeners to Reactive (Observables) using RxJava?

I'm using a multiplayer Game Client that's called AppWarp (http://appwarp.shephertz.com), where you can add event listeners to be called back when event's happen, let's assume we'll be talking about the Connection Listener, where you need to implement this interface:
public interface ConnectionRequestListener {
void onConnectDone(ConnectEvent var1);
void onDisconnectDone(ConnectEvent var1);
void onInitUDPDone(byte var1);
}
My goal here is to mainly create a Reactive version of this client to be used in my Apps Internally instead of using the Client itself directly (I'll also rely on interfaces later instead of just depending on the WarpClient itself as in the example, but that's not the important point, please read my question at the very end).
So what I did is as follows:
1) I introduced a new event, named it RxConnectionEvent (Which mainly groups Connection-Related events) as follows:
public class RxConnectionEvent {
// This is the original connection event from the source client
private final ConnectEvent connectEvent;
// this is to identify if it was Connection / Disconnection
private final int eventType;
public RxConnectionEvent(ConnectEvent connectEvent, int eventType) {
this.connectEvent = connectEvent;
this.eventType = eventType;
}
public ConnectEvent getConnectEvent() {
return connectEvent;
}
public int getEventType() {
return eventType;
}
}
2) Created some event types as follows:
public class RxEventType {
// Connection Events
public final static int CONNECTION_CONNECTED = 20;
public final static int CONNECTION_DISCONNECTED = 30;
}
3) Created the following observable which emits my new RxConnectionEvent
import com.shephertz.app42.gaming.multiplayer.client.WarpClient;
import com.shephertz.app42.gaming.multiplayer.client.events.ConnectEvent;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.subscriptions.Subscriptions;
public class ConnectionObservable extends BaseObservable<RxConnectionEvent> {
private ConnectionRequestListener connectionListener;
// This is going to be called from my ReactiveWarpClient (Factory) Later.
public static Observable<RxConnectionEvent> createConnectionListener(WarpClient warpClient) {
return Observable.create(new ConnectionObservable(warpClient));
}
private ConnectionObservable(WarpClient warpClient) {
super(warpClient);
}
#Override
public void call(final Subscriber<? super RxConnectionEvent> subscriber) {
subscriber.onStart();
connectionListener = new ConnectionRequestListener() {
#Override
public void onConnectDone(ConnectEvent connectEvent) {
super.onConnectDone(connectEvent);
callback(new RxConnectionEvent(connectEvent, RxEventType.CONNECTION_CONNECTED));
}
#Override
public void onDisconnectDone(ConnectEvent connectEvent) {
super.onDisconnectDone(connectEvent);
callback(new RxConnectionEvent(connectEvent, RxEventType.CONNECTION_DISCONNECTED));
}
// not interested in this method (for now)
#Override
public void onInitUDPDone(byte var1) { }
private void callback(RxConnectionEvent rxConnectionEvent)
{
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(rxConnectionEvent);
} else {
warpClient.removeConnectionRequestListener(connectionListener);
}
}
};
warpClient.addConnectionRequestListener(connectionListener);
subscriber.add(Subscriptions.create(new Action0() {
#Override
public void call() {
onUnsubscribed(warpClient);
}
}));
}
#Override
protected void onUnsubscribed(WarpClient warpClient) {
warpClient.removeConnectionRequestListener(connectionListener);
}
}
4) and finally my BaseObservable looks like the following:
public abstract class BaseObservable<T> implements Observable.OnSubscribe<T> {
protected WarpClient warpClient;
protected BaseObservable (WarpClient warpClient)
{
this.warpClient = warpClient;
}
#Override
public abstract void call(Subscriber<? super T> subscriber);
protected abstract void onUnsubscribed(WarpClient warpClient);
}
My question is mainly: is my implementation above correct or should I instead create separate observable for each event, but if so, this client has more than 40-50 events do I have to create separate observable for each event?
I also use the code above as follows (used it in a simple "non-final" integration test):
public void testConnectDisconnect() {
connectionSubscription = reactiveWarpClient.createOnConnectObservable(client)
.subscribe(new Action1<RxConnectionEvent>() {
#Override
public void call(RxConnectionEvent rxEvent) {
assertEquals(WarpResponseResultCode.SUCCESS, rxEvent.getConnectEvent().getResult());
if (rxEvent.getEventType() == RxEventType.CONNECTION_CONNECTED) {
connectionStatus = connectionStatus | 0b0001;
client.disconnect();
} else {
connectionStatus = connectionStatus | 0b0010;
connectionSubscription.unsubscribe();
haltExecution = true;
}
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
fail("Unexpected error: " + throwable.getMessage());
haltExecution = true;
}
});
client.connectWithUserName("test user");
waitForSomeTime();
assertEquals(0b0011, connectionStatus);
assertEquals(true, connectionSubscription.isUnsubscribed());
}
I suggest you avoid extending the BaseObservable directly since it's very error prone. Instead, try using the tools Rx itself gives you to create your observable.
The easiest solution is using a PublishSubject, which is both an Observable and a Subscriber. The listener simply needs to invoke the subject's onNext, and the subject will emit the event. Here's a simplified working example:
public class PublishSubjectWarpperDemo {
public interface ConnectionRequestListener {
void onConnectDone();
void onDisconnectDone();
void onInitUDPDone();
}
public static class RxConnectionEvent {
private int type;
public RxConnectionEvent(int type) {
this.type = type;
}
public int getType() {
return type;
}
public String toString() {
return "Event of Type " + type;
}
}
public static class SimpleCallbackWrapper {
private final PublishSubject<RxConnectionEvent> subject = PublishSubject.create();
public ConnectionRequestListener getListener() {
return new ConnectionRequestListener() {
#Override
public void onConnectDone() {
subject.onNext(new RxConnectionEvent(1));
}
#Override
public void onDisconnectDone() {
subject.onNext(new RxConnectionEvent(2));
}
#Override
public void onInitUDPDone() {
subject.onNext(new RxConnectionEvent(3));
}
};
}
public Observable<RxConnectionEvent> getObservable() {
return subject;
}
}
public static void main(String[] args) throws IOException {
SimpleCallbackWrapper myWrapper = new SimpleCallbackWrapper();
ConnectionRequestListener listner = myWrapper.getListener();// Get the listener and attach it to the game here.
myWrapper.getObservable().observeOn(Schedulers.newThread()).subscribe(event -> System.out.println(event));
listner.onConnectDone(); // Call the listener a few times, the observable should print the event
listner.onDisconnectDone();
listner.onInitUDPDone();
System.in.read(); // Wait for enter
}
}
A more complex solution would be to use one of the onSubscribe implementations to create an observable using Observable.create(). For example AsyncOnSubscibe. This solution has the benefit of handling backperssure properly, so your event subscriber doesn't become overwhelmed with events. But in your case, that sounds like an unlikely scenario, so the added complexity is probably not worth it.

How to reimplement Java listeners with anonymous classes in C#

I am trying to replicate my Java code in C# and I wish to know how can I replicate this Java functionality in C#.
Util.java
public class Util
{
public void function(String s, final SetAvailabilityStatusListener setStatusListener)
{
// ....
}
public static interface SetAvailabilityStatusListener {
public void setAvailabilityStatus(Status status);
}
}
Activity.java
public class Activity
{
public void anotherFunction()
{
util.function("name", new SetAvailabilityStatus()
{
#Override
public void setAvailabilityStatus(Status status) {
loginSetAvailabilityStatus(status);
}
}
}
}
Use delegates. They are used in C# instead of Java anonymous classes that implement interfaces.
public class Util
{
public void Function(String s, Action<Status> setStatusListener)
{
// ....
setStatusListener("myStatus");
}
}
public class Activity
{
private Util util = new Util();
public void AnotherFunction()
{
util.Function("name", status => LoginSetAvailabilityStatus(status));
}
public void LoginSetAvailabilityStatus(string status){
//do something with status
}
}
I was unable to find suitable duplicate, so:
1. C# does not have anonymous classes like Java does, but no one stops you from creating needed listener classes manually
public class Util
{
public void Function(String s, ISetAvailabilityStatusListener setStatusListener)
{
// ....
}
public interface ISetAvailabilityStatusListener {
public void SetAvailabilityStatus(Status status);
}
}
public class Activity
{
private class MySetAvailabilityStatusListener: Util.ISetAvailabilityStatusListener
{
public void SetAvailabilityStatus(Status status)
{
// do your handling, but nested classes have some differences with anonymous Java classes, so it may require additional infrastructure.
}
}
public void AnotherFunction()
{
utilObj.Function("name",
new MySetAvailabilityStatusListener())
}
}
It is so-called observer design pattern (just without unregistration method!!).
2. As it has been already suggested by #AndreySarafanov you can use Action Delegates and lambda expressions:
public class Util
{
public void Function(String s, Action<Status> statusChangeListener)
{
// ....
}
}
public class Activity
{
public void AnotherFunction()
{
utilObj.Function("name",
(status) =>
{
loginSetAvailabilityStatus(status);
}
}
}
3. C# has another more simple mechanism to deal with event-handling(subsrciption) mechanics - events and delegates
public class StatusEventArgs : EventArgs
{
//...
}
public class Util
{
public void SomeFunction()
{
// ....
if (this.OnAvailabilityChanged != null)
OnAvailabilityChanged(this, new StatusEventArgs(status));
}
public event EventHandler<StatusEventArgs> OnAvailabilityChanged
}
public class Activity
{
public void AvailabilityStatusChangedHandler(object sender, EventArgs<Status> eventArgs)
{
}
public void AnotherFunction()
{
utilObj.OnAvailabilityChanged += this.AvailabilityStatusChangedHandler;
}
}
It does not allow you to associate the name property with event handler, well, you can overcome it with special registration method, but it will reduce the usability of events, so you should probably stick with another solution.

Having trouble getting the observer pattern working

I have been trying to no avail to get the observer pattern working in a relatively simple application.
I have 4 GUI classes
StarterClass (contains a CompositeWordLists and a CompositeWordListData)
CompositeWordLists (contains many CompositeListItem/s and a CompositeWordListData)
CompositeListItem
CompositeWordListData (Contains a DialogWordData)
DialogWordData
Here is my Observable
interface Observable<T> {
void addObserver(T o);
void removeObserver(T o);
void removeAllObservers();
void notifyObservers();
}
And I am creating Observers like this:
public class Observers {
private Observers(){};
interface WordListsObserver {
public void update(CompositeWordLists o);
}
interface ListItemObserver {
public void update(CompositeListItem o);
}
}
Basically I am having trouble with specifying the sort of event that occurred. For example, the CompositeWordLists class needs to know when a CompositeListItem is deleted, saved edited etc but I only have one update method ... my brain hurts now!
What is a better way of doing this?
UPDATE
Still having trouble with this, I added events and changed Observable and Observers but now I have type safety problems.
public class Observers {
private Observers(){};
/**
* #param <T> the object that is passed from the Observable
*/
interface ObservableEvent<T> {
T getEventObject();
}
/**
* Get notified about Authentication Attempts
*/
interface ObserverAuthenticationAttempt {
/**
* #param e true if authentication was successful
*/
public void update(ObservableEvent<Boolean> e);
}
/**
* Get notified about a Word Deletion
*/
interface ObserverWordDeleted {
/**
* #param e the id of the word that was deleted
*/
public void update(ObservableEvent<Integer> e);
}
}
The Observable Interface now looks like this
interface Observable<T> {
void addObserver(T o);
void removeObserver(T o);
void removeAllObservers();
<K> void notifyObservers(Observers.ObservableEvent<K> e);
}
The problem is that when I implement this I get and would have to cast K to the appropriate type, not really what I want to do.
#Override
public <K> void notifyObservers(ObservableEvent<K> e) {
for(Observers.ObserverAuthenticationAttempt o : this.observers)
o.update(e);
}
What am I doing wrong?
update 2
Actually it works better with an Observable like this, but I still need to specify the correct EventType in two different places.
interface Observable<T,K> {
void addObserver(T o);
void removeObserver(T o);
void removeAllObservers();
void notifyObservers(Observers.ObservableEvent<K> e);
}
You do not need to parametrise the Observers, but you need to parametrize the events.
public interface Observer<T> {
void notify(T event);
}
An example event:
public class WordListUpateEvent {
private final int changedIndex;
public WordListUpateEvent(int changedIndex) {
this.changedIndex = changedIndex;
}
public int getChangedIndex() {
return changedIndex;
}
}
Then you can have different interface of it for example:
public interface WordListObserver extends Observer<WordListUpateEvent> {}
and its implementations
public class ConcreteWordListObserverA implements WordListObserver {
#Override
public void notify(WordListUpateEvent event) {
System.out.println("update item at index: " + event.getChangedIndex());
}
}
on the other hand you need your Observable interface, i have splitted it in two interface in order ti make the notifyObservers method not public to the observers (you will see it later):
public interface Observable<T> extends ObservableRegistration<T> {
void notifyObservers(T event);
}
public interface ObservableRegistration<T> {
void addObserver(Observer<T> o);
void removeObserver(Observer<T> o);
void removeAllObservers();
}
If you would have several observables in a subject, you can not implemnt the Observalbe interface direct to your subject, so you need a seperate implementation class:
public class ObservableImpl<T> implements Observable<T>{
private final List<Observer<T>> observers = new ArrayList<Observer<T>>();
#Override
public void addObserver(Observer<T> o) {
this.observers.add(o);
}
#Override
public void removeObserver(Observer<T> o) {
this.observers.remove(o);
}
#Override
public void removeAllObservers() {
this.observers.clear();
}
#Override
public void notifyObservers(T event) {
for(Observer<T> observer : observers) {
observer.notify(event);
}
}
}
Now you can use the implementation in your subject:
public class Subject {
private Observable<WordListUpateEvent> wordListObservable = new ObservableImpl<WordListUpateEvent>();
//private Subject<OtherEvent> otherObservable = new ObservableImpl<WordListUpateEvent>();
public ObservableRegistration<WordListUpateEvent> getWordListObservableRegistration() {
return this.wordListObservable;
}
// public ObservableRegistration<OtherEvent> getOtherRegistration() {
// return this.otherObservable;
// }
public void doSomething() {
this.wordListObservable.notifyObservers(new WordListUpateEvent(42));
}
}
And this is how you can connect the observer and the subject:
public class Start {
public static void main(String[] args) {
Subject subject = new Subject();
subject.getWordListObservableRegistration().addObserver(new ConcreteWordListObserverA());
subject.getWordListObservableRegistration().addObserver(new ConcreteWordListObserverA());
subject.doSomething();
}
}
I would create an Observer interface, containing a public void update(ObservableEvent oe) method, and an ObserverEvent interface. After that, you can create specific class for each of your events.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Observer.html
http://www.java2s.com/Code/Java/Design-Pattern/Observableandobserver.htm
The Java Observer's update method has the Object argument. You can pass any Object, thus you can create your own "UpdateMessage" Object that can contain the updated object and additional information about what happend (deleted, saved etc.).

Categories

Resources