Visitor design pattern with GWT - java

I had an idea and it goes like this:
Parse a file on service side.
Create a list of actions based on the file's contents.
Pass the list of actions to the client side.
Have the client define and perform actions based on the items on the list.
As in the visitor pattern, we'd have a class for the actions and all of them inherit the Action interface. The clients would then implement the visitors. In Java it'd be something like this:
public interface Action {
void act(Visitor visitor);
}
public class PerfectAction implements Action {
void act(Visitor visitor) {
visitor.bePerfect();
}
}
public class VisibleAction implements Action {
void act(Visitor visitor) {
visitor.beVisible();
}
}
public interface Visitor {
void bePerfect();
void beVisible();
}
The Problem
I can't create Proxy classes for the Action and Visitor interfaces. They do not contain setters and/or getters. Plus they do not contain any data. Is it possible to pass this knowledge of which method should be called on the Visitor object from service to client side?

Request Factory can only move data around (EntityProxy and/or ValueProxy), and ask the server to do things on behalf of the client (RequestContext).
To transfer actions, the client and server first need to share the knowledge of those actions that can be performed.
You then have two solutions:
move to GWT-RPC
because the client has to know every possible action upfront anyway, create an enum or whatever to identify each action, and transfer those identifiers to the client, which will map them back to concrete actions to perform.

I don't think this is how you'd implement the visitor pattern. I'd do something like this
public interface ActionVisitor {
void visit(VisibleAction va);
void visit(PerfrectAction pa);
}
public class PerfectAction implements Action {
void act(Visitor visitor) {
visitor.visit(this);
}
}
public class VisibleAction implements Action {
void act(Visitor visitor) {
visitor.visit(this);
}
}
Then I'd define an implementation of the visitor that performed the appropriate actions.
It's important to define it in this way so that the logic of what the visitor does is external to the class. Prior to this, each implementation had a different implementation of the visitor, so it'd be harder to change behaviour.
I think that this will solve your problem, because now the logic of what to do is externalized to the visitor.

Related

Avoid using instanceof Patterns

I want to avoid the using of instanceof:
here is my case :
The definition of my Events classes are in a commons module :
public class Event1 extends AbstractEvent{
}
public class Event2 extends AbstractEvent{
}
public class Event3 extends AbstractEvent{
}
in another module called jms i have a listener that receive Event message from a queue :
public class MyMessageListener implements MessageListener {
#Override
public void onMessage(Message message) {
// CONVERT message to Event Object
if (event instanceof Event1) {
// Execute Processing 1
}
if (event instanceof Event2) {
// Execute Processing 2
}
if (event instanceof Event3) {
// Execute Processing 3
}
}
I want to avoid using instanceof and the best things for doing this is the visitor pattern with an execute method in the AbstractEvent and every leaf classes will implement it .
My problem is that in the common package i don't have access to the classes responsible for the processing . theses classes exist only in the jms module .
Is there any Tips or hint to do this (Advanced Visitor) or another pattern to do that
Put all possible behaviours to Map<Class, Runnable> and match event's type and Runnable type.
In such cases, the visitor Pattern can sometimes help. The visitor pattern is mainly suitable if your class hierarchy doesn't change much, because for each change in the class hierarchy you also must change the visitor (but that is also the case if you're using `instanceof').
To use the visitor pattern, you need to define a Visitor interface which contains a visit method for all types you want to visit:
interface Visitor {
visit(Event1 event);
visit(Event2 event);
visit(Event3 event);
}
first you want a common superclass which is the root for all classes you want to apply the visitor to. This superclass contains a method callVisitor:
public abstract class MyEvent extends AbstractEvent {
public abstract void visit(Visitor v);
}
public class Event1 extends MyEvent{
public void visit(Visitor v) {
v.visit(this); // calls visit(Event1)
}
}
public class Event2 extends MyEvent{
public void visit(Visitor v) {
v.visit(this); // calls visit(Event2)
}
}
public class Event3 extends MyEvent{
public void visit(Visitor v) {
v.visit(this); // calls visit(Event3)
}
}
Finally, you can create a visitor instance every time you need different behaviour based on the runtime type of the class:
public void onMessage(Message message) {
Visitor v = new Visitor() {
public void visit(Event1 event) {
// Execute Processing 1
}
public void visit(Event2 event) {
// Execute Processing 2
}
public void visit(Event3 event) {
// Execute Processing 3
}
}
event.visit(v);
}
The visitor pattern might be overkill in your situation, but I find it useful sometimes. The major advantage over using instanceof and other possible solutions is that it is typesafe: if you add a class to the hierarchy, the project will not compile until you added a visitor method to all visitors you defined.
As an alternative approach to the other answers, you could move the decision logic into your messaging configuration, so that each type of event is consumed by a MessageListener dedicated to processing only one type of Event. This will remove any "if" logic from your Consumer.
A caveat to this approach is that multiple consumers may process the events out of order. If this is an issue for your problem domain you may not wish to deal with the out-of-sequence issues yourself.
See JMS Selectors for more information
The advantages to this approach are:
Consumers are responsible for only one Event type (simplification)
You can add more Consumers independently based on event type (scalability)
You could have the AbstractEvent declare an abstract isOfType() method:
public abstract class AbstractEvent {
public abstract boolean isOfType( String type );
}
It would eliminate the instanceof's but not the if switching, though...
Cheers,

Visitor design pattern intent : misleading or I am missing something?

in the reference book "Design Patterns Elements of Reusable Object-Oriented Software" by the gang of four, the intent of the visitor pattern is explained as follow :
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Another advantage I read about the visitor pattern is that:
ADD A NEW OPERATION WITHOUT HAVING THE SOURCE CODE OF THE CLASSES..
I made a deep search in Google, but I did not find any example showing how to do that.
So let's take a simple example :
public interface MyInterface {
public void myMethod();
}
public class MyClassA implements MyInterface {
/* (non-Javadoc)
* #see com.mycomp.tutorials.designpattern.behavorials.MyInterface#myMethodA()
*/
public void myMethod() {
System.out.println("myMethodA implemented in MyClassA");
}
}
public class MyClassB implements MyInterface {
/* (non-Javadoc)
* #see com.mycomp.tutorials.designpattern.behavorials.MyInterface#myMethodA()
*/
public void myMethod() {
System.out.println("myMethod implemented in MyClassB");
}
}
So how would I add a new method myNewMethod() to this hierarchy of classes without changing them, using the visitor pattern?
You example is not a visitor pattern. It is just inheritance.
A visitor pattern first requires an visitor interface
interface ThingVisitor {
void visit(ThingA a);
void visit(ThingB b);
}
Now you need an interface Thing:
interface Thing {
void accept(ThingVisitor visitor);
}
And your implementation of, for example, ThingA would be
class ThingA implements Thing {
public void accept(final ThingVisitor visitor) {
visitor.visit(this);
}
}
Now you see the logic to handle the Thing types is contained in the implementations of ThingVisitor.
Let's say you have a Message class, and 2 subclasses Email and Sms.
You could have many operations on these two classes, like sendToOnePerson(), sendToSeveralPeople(). But you probably don't want to have these methods in the Email and Sms class directly, because it tightly couples them to the SMTP/phone system. And you would also like to be able to add other operations in the futre, like forward() or delete(), or whatever. So the first implementation you could use is
public void delete(Message message) {
if (message instanceof Email) {
deleteEmail(Email) message);
}
else if (message instanceof Sms) {
deleteSms((Sms) message);
}
}
But this is ugly: it's not object-oriented, and it will fail if there is a new VoiceMessage subclass appearing.
An alternative is to use the visitor pattern.
public interface MessageVisitor {
void visitEmail(Email email);
void visitSms(Sms sms);
}
public abstract class Message {
public void accept(MessageVisitor visitor);
}
public class Email extends Message {
#Override
public void accept(MessageVisitor visitor) {
visitor.visitEmail(this);
}
}
public class Sms extends Message {
#Override
public void accept(MessageVisitor visitor) {
visitor.visitSms(this);
}
}
This way, to implement send(), all you need is a MessageVisitor implementation that can send an email and send an Sms:
SendMessageVisitor visitor = new SendMessageVisitor();
message.accept(visitor);
And if you introduce a new delete() operation, you don't have to touch to Message classes at all. All you need is a DeleteMessageVisitor:
DeleteMessageVisitor visitor = new DeleteMessageVisitor();
message.accept(visitor);
So, basically, it's a bit like if you added polymorphic methods to the Message classes by not actually modifying the Message classes.
The visitor pattern assumes that you have a method in the classes you want to "visit" which accepts and executes the visitor, here is an example. The pattern is not motivated by adding functionality to foreign classes but to localize functionality in the visitors which would otherwise be spread over several classes, e.g. for saving elements (see the example).
Quick description of the visitor pattern.
The classes that require modification must all implement the 'accept' method. Clients call this accept method to perform some new action on that family of classes thereby extending their functionality. Clients are able to use this one accept method to perform a wide range of new actions by passing in a different visitor class for each specific action. A visitor class contains multiple overridden visit methods defining how to achieve that same specific action for every class within the family. These visit methods get passed an instance on which to work

Generic callback in Java

What should be the preferable Java interface or similar pattern that could be used as a generic callback mechanism?
For example it could be something like
public interface GenericCallback
{
public String getID();
public void callback(Object notification);
// or public void callback(String id, Object notification);
}
The ID would be needed for cases of overriden hashCode() methods so that the callee identifies the caller.
A pattern like the above is useful for objects that needs to report back to the class they were spawned from a condition (e.g., end of processing).
In this scenario, the "parent" class would use the getID() method of each of these GenericCallback objects to keep a track of them in a Map<String, GenericCallable> and add or remove them according to the notification received.
Also, how should such an interface be actually named?
Many people seem to prefer the Java Observer pattern, but the Observable class defined there is not convenient, since it not an interface to circumvent single inheritance and it carries more functionality than actually needed in the above, simple scenario.
I would genericize the callback, based upon the type of Object passed. This is particularly useful for EventListeners listening for different classes of events. e.g.
public interface Callback<T> {
public void callback(T t);
}
You may be able to use the type T as the key in a Map. Of course, if you want to differentiate between two callbacks that take the same argument, like a String, then you'd need something like your getID().
Here my old blog about using this for Event Listeners The interface Events.Listener corresponds to Callback<T> above. And Broadcasters uses a Map to keep track of multiple listeners based upon the class they accept as the argument.
I'd recommend using Observer pattern since the Observer pattern is the gold standard in decoupling - the separation of objects that depend on each other.
But I'd recommend avoiding using the Java.util.Observable class if you are looking for a generic callback mechanism. Because Observable has a couple of weaknesses: it's not an interface, and forces you to use Object to represent events.
You can define your own event listener like this:
public class MyEvent extends EventObject {
public MyEvent(Object source) {
super(source);
}
}
public interface MyEventListener {
void handleEvent(EventObject event);
}
public class MyEventSource {
private final List<MyEventListener> listeners;
public MyEventSource() {
listeners = new CopyOnWriteArrayList<MyEventListener>();
}
public void addMyEventListener(MyEventListener listener) {
listeners.add(listener);
}
public void removeMyEventListener(MyEventListener listener) {
listeners.remove(listener);
}
void fireEvent() {
MyEvent event = new MyEvent(this);
for (MyEventListener listener : listeners) {
listener.handleEvent(event);
}
}
}
looks like you want to implement the Observer pattern. In this url is a complete implementation for the observer pattern in Java. In your case the observer will be the callback.
Also If you need to implement something more complex, you will end up doing an event/notifier pattern. Take a look at this other pattern here.
Thanks,
#leo.
Callbacks in Java8 can now be done with the java.util.function package.
See Java 8 lambda Void argument for more information.

How should I design this code (parallel class hierarchies)?

I have a set of apps that all need to synchronize with a webservice:
download some XML from a webservice.
parse that XML.
then update the database to match the parsed XML.
I'd like to keep as much of the relevant code as possible in a common library to avoid duplication, and I'd like to have the different apps all slot their parsing and updating code into a fairly simple common framework.
So there's a common sync() method:
public void sync(URI updateUrl, XMLParser parser, Updater animalUpdater) {
String raw = getXML();
List<ParsedAnimal> parsed = parser.parse(raw);
// try:
// begin transaction
for (ParsedAnimal pi : parsed) {
animalUpdater.updateItem(pi);
}
// commit transaction
// catch: rollback transaction, rethrow
// finally: close database connection
}
The parser returns either a ParsedCat, or ParsedDog, or whatever, all of which inherit from a common ParsedAnimal class:
public abstract class ParsedAnimal {...}
public class ParsedCat extends ParsedAnimal {...}
public class ParsedDog extends ParsedAnimal {...}
Then I have an Updater which needs to take the parsed item and inject the contents into the database:
public abstract class Updater {
public abstract void updateItem(ParsedAnimal parsed);
}
public class CatUpdater extends Updater {
#Override
public void updateItem(ParsedCat parsed) {}
}
public class DogUpdater extends Updater {...}
This doesn't work — the contract for Updater specifies that updateItem() accepts a ParsedAnimal, and CatUpdater and DogUpdater both break that contract by only accepting a specific type of animal.
What I have is a parallel class hierarchy — ParsedX matches up one to one with XUpdater. The Code Smells page on Coding Horror suggests merging the two class hierarchies into a single hierarchy, but I feel like the "thing being worked on" and the "thing doing the working" are different enough that they should be separate classes.
Is there a neat way of structuring this, or some design pattern that would come in handy?
Generics can come in handy for your issue with the Updater contract:
public abstract class Updater<T extends ParsedAnimal> {
public abstract void updateItem(T parsed);
}
public class CatUpdater extends Updater<ParsedCat> {
#Override
public void updateItem(ParsedCat parsed) {}
}
public class DogUpdater extends Updater<ParsedDog> {...}
However, your sync method has an Updater as a param that it tries to use for all parsed items. This won't work. If you're going to have a separate Updater per parsed type, you'll need to get instantiate the updater based on which parse result your have. This can be handled by some form of "Factory". For a start, you might want to look at using the Factory Method pattern.
updateItem(ParsedAnimal parsed){
if (parsed instanceof ParsedCat) {
...
} else if (parsed instanceof ParsedDog) {
...
}
}

Observer pattern with two lists of observers

I have a class MyObserver that listens to changes in Notifier. Notifier extends Observable and notify its events with notifyObservers(Object). The object passed as argument is always an instance of the same class. The problem is that each observer need to listen to diferent events. For example one observer needs to listen to state changed events and others to all types of events. How can I do this with observer pattern?
Thanks.
Use notifyObservers(Object arg) version and create some sort of "event type" object to stick in there. In your observing classes simply filter on the passed in event class.
public void update(Object observable, Object arg) {
if ( (MyEvent) arg.isEventX() ) { /* do stuff */ }
}
I think that the Java built-in implementation of the Observer Pattern is not suitable for your case.
In fact, the general Observer pattern is usable when just one Observable kind of events can arise. In the Observer Design Pattern, all the Observes get notified always.
So, in this case, you need to extend the general Observer pattern, by defining your own Observable interface, for example, this way:
public enum EventKind {
EVENT_A, EVENT_B, EVENT_C;
}
public interface Observable {
public void registerObserver(EventKind eventKind);
public void unregisterObserver(EventKind eventKind);
public void notifyObservers(EventKind eventKind);
}
Then you can just implement this Observable interface with internal lists for each kind of event to notify. You can still use the Java built-in Observer interface if you wish.
This approach has the following benefits:
You can flexibly add more kind of events
without affecting the code of the
Observers.
You can register any observer to any
event.
You update just the Observers
that are effectively interested in
each event.
You avoid "empty methods", "event type checking" and other
tricks on the Observers side.
If you can change the design a bit:
interface MyObserver {
public void stateChangeEvent();
public void otherEvent();
}
class MyObserverAdapter implements MyObserver {
public void stateChangeEvent() {
// some default implementation or no implementation.
}
public void otherEvent() {
// some default implementation or no implementation.
}
}
class MyStateChangeObserver extends MyObserverAdapter {
public void stateChangeEvent() {
// implement behavior specific to this class.
}
}
class MyOtherObserver extends MyObserverAdapter {
public void otherEvent() {
// implement behavior specific to this class.
}
}
Usage:
MyObserver stateObserver = new MyStateChangeObserver();
MyObserver otherObserver = new MyOtherObserver();
notifier.notifyObservers(stateObserver);
notifier.notifyObservers(otherObserver);
You can test for a state change by doing the following in the Observable class:
public void update(Observable o, Object arg)
{
if(o.hasChanged())
{
// do something
}
}
The observers that listen to anything don't need this test. This is probably the easiest way if you only want to listen for state changes.

Categories