Hot Posts

Other patterns: Facade, Decorator, Observer and much more

We have looked in depth at two of the most used patterns. Now I would like to take quick look at a few more patterns that have benefited from changes in the Enterprise programming model.

Lets have a quick whistle stop tour of other patterns that have been changes in Java EE.

Façade Pattern

Java EE provides an annotation that dictates the statefulness of the façade. The façade can annotated either as stateful or stateless, depending on whether the use case requires state to be maintained or not.

In this code snippet the AccountService is injected into the BankServiceFacade and state will not be maintained.

Decorator Pattern

The decorator pattern is one of the Structural Pattern and dynamically adds logic to an object.

It is the only pattern that requires XML configuration in the bean.xml file, but only if decorator order is not specified by the priority annotation.

Two new annotations are introduced: @Decorator and @Delegate

@Decorator – annotates the decorator class
@Delegate – annotates the delegate injection point where the class to be decorated is injected

@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public class PriceDiscountDecorator implements Product {

    @Any
    @Inject
    @Delegate
    private Product product;

    public String generateLabel() {
        product.setPrice(product.getPrice() * 0.5);
        return product.generateLabel();
    }

}

Decorators with the lower priority are called first.

All instances of Product are injected into this class and when a call is made to the generateLabel method of any product instance the container intercepts it. The call is delegated to that appropriate method of the PriceDiscountDecorator where it discounts the product’s price and passes the call onto the original destination by calling generateLabel method of the given product instance.

Observer Pattern

The observer pattern is a Behavioural Pattern.

Maintains a list of its dependants and notifies them automatically of any state changes, usually by calling one of their methods. Objects subscribe to receive information when changes occurs.

Any method parameter annotated @Observes listens for events the type of that parameter.

public void trace(@Observes String message){
     // response to String event
}

In this code snippet we are listening for events of type String. When an event of type String occurs the trace method receives the object that produced the event.

Next: Final conclusions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: