Getting Started With JMS-ActiveMQ: Explained in a Simple Way

Java Message Service (JMS) is a very useful open source that works as a message-oriented middleware.

About JMS

  • The Java Message Service (JMS) API is a messaging standard that allows application components based on the Java Platform Enterprise Edition (Java EE) to create, send, receive, and read messages.
  • It enables distributed communication that is loosely coupled, reliable, and asynchronous.
  • Messaging is a technique to communicate with different software components and/or applications.
  • JMS, a messaging service, is mainly used to send and receive messages from one application to another.
  • There are different JMS brokers/providers like ActiveMQ, RabbitMQ, OpenMQ, etc.
  • I will be using ActiveMQ for this tutorial.

About ActiveMQ

  • ActiveMQ is a messaging service that facilitates disparate data at scale in enterprise systems. 
  • ActiveMQ is a popular open-source messaging service that is built in Java. 
  • It works as a message-oriented middleware or MoM for short.

Setting Up ActiveMQ

  • Java must be installed and set up (JAVA_HOME and PATH variables). I am using Java 8 for this tutorial.
  • Download ActiveMQ (we will use "Classic" for this tutorial)

ActiveMQ classic

Using the Prototype Design Pattern In Java

Let's discuss today another creational design pattern named - Prototype Design Pattern.

Prototype Design Pattern

  • The Prototype Design Pattern is one of the twenty-three well-known GoF design patterns  which helps us copying an existing object rather than creating a new instance from scratch.
  • The Prototype pattern is used when we need to create a number of instances of a class and  each instance has almost same state or has very little difference.
  • The Prototype pattern is used when creation of actual object directly is costly as per resource and data it holds and also is a time taking.
  • The existing original object acts as a prototype and contains the state of the object. The new object is copy of the original object.
  • The Prototype pattern is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
  • We are free to change values in the newly copied object whenever we required. 
  • The Prototype pattern helps us to save costly resources and time, especially when the object creation is a heavy and time taking process.
  • In Java, One of the best available way to create object from existing objects are by using clone() method of Cloneable interface. Clone is the simplest approach to implement prototype pattern.
  • We can also implement Prototype interface by using Deep Copy method. 
    • Deep Copy - By Deep copy we create an object by copying all the fields of the original object. And also if the original object contains other objects as fields, we copy them as well. 
    • Shallow Copy - By Shallow copy we create an object by copying all the fields of the original object. But if the original object contains other objects as fields, we copy only the reference of those objects instead of copying complete object itself.
  • There are two ways of implementing the Prototype pattern
    • Basic Implementation
    • Prototype Registry Implementation

Basic ImplementationBasic Implementation

Using Template Method Design Pattern In Java

Today, I will discuss another very useful design pattern named the Template Method Design Pattern.

Template Method Design Pattern

  • The Template Method pattern is one of the behavioral design patterns identified by Gamma et al. in the book Design Patterns.
  • The Template Method pattern provides a method in a super-class, usually an abstract super-class, and defines the skeleton of an operation in terms of several high-level steps.
  • Generally, these steps are implemented by additional helper methods in the same class as the template method. 
  • The helper methods may be either created as an abstract method, for which sub-classes are required to provide concrete implementations, or hook methods, which have empty bodies in the super-class. 
  • The Template Method design pattern is used to define an algorithm as a skeleton of operations and leave the details to be implemented by the child classes.
  • In this way of implementation, the overall structure and sequence of the algorithm are preserved by the parent class.
  • The Template Method pattern defines the sequential steps to execute a multi-step algorithm. We can provide a default implementation as well.
  • In the Template Method pattern, we define a preset structure method called template method which consists of steps. 
  • These steps can be created as an abstract method which will be implemented by its sub-classes. 
  • In the Template Method pattern, an abstract class exposes defined way(s)/template(s) to execute its methods.
  • The template method uses and defines the sequence of steps to perform the algorithm.

abstract template class

Mediator Design Pattern In Java

Let's finish some remaining design patterns to cover this topic. Today, I will discuss another design pattern - Mediator Design Pattern.

Mediator Design Pattern

  • The Mediator Design Pattern is one of the Gang of Four design patterns which is used to control and reduce complexity of communication among groups of objects.
  • The Mediator Pattern is a behavioral pattern which defines an object to encapsulate the interaction between objects.
  • The Mediator Pattern helps us to reduce chaotic dependencies between objects. 
  • The Mediator pattern helps us to restrict any direct communication between the objects and allow us to collaborate objects only via a mediator object.
  • By using Mediator object we can control communication between objects.
  • The Mediator object also hides the complexity of communication between objects.
  • The Mediator pattern defines a mediator class to handle all the communications between different classes. That also supports easy maintenance of the communication related code by using loose coupling.
  •  The Chatting Application is a good example of Mediator pattern where a group of chat users communicates with each other via the char server.
  • The Whatsapp is another good example of the Mediator pattern. Whatsapp server handles all the communication between different whatsapp users.
  • Air Traffic Control System is also another great example in which all flights doing takeoff or landing communicates with the Air Traffic Control to manage their safe and smooth movement.

mediator design pattern

Let's take an example of communication between different workers; each one is assigned to a dedicated type of job to perform. We will see how they can communicate with others with the help of manager for the jobs they are not doing. I will not use multi-threading or network related code just to make the example as simple as possible. 

Using Filter Design Pattern In Java

Lets discuss another very useful design pattern named - Filter Design Pattern.

Filter Design Pattern

  • The Filter Design Pattern also known as Criteria Design Pattern.
  • The Filter Design Pattern is a design pattern that allows developers to filter a set of objects using different criteria/filter condition and chaining them in a decoupled way through logical operations. 
  • The Filter Design Pattern is a structural pattern which can combines multiple criteria to obtain single criteria.
  • With the use of Lambda Expressions in Java 8, it is actually very simple to use without even thinking this as a design pattern. But, if we are aware of the concept of filtering, we will have better understanding and command over the implementation of the code.
  • There are two different ways of creating filters
    • Filter for Entire collection.
    • Filter for single member of the collection. 
  • I will try to highlight use of lambda for filtering as well under this article. But this article is not about Java Lambda Expressions. Based on the viewer's response I may write another article to cover basics of lambdas as well. 


class filter design pattern

Using Flyweight Design Pattern In Java

I am here to discuss another structural design pattern named Flyweight Design Pattern. 

Flyweight Design Pattern

  • The Flyweight Design Pattern is a Structural Design Pattern and one of the Gang of Four design patterns
  • The Flyweight pattern is used to minimize the memory usage by sharing as much data as possible with other similar objects.
  • The Flyweight pattern provides a way to reduce the number of objects created and to decrease memory footprint and increase performance.
  • The Flyweight pattern tries to reuse already existing similar kind objects by storing them in a collection which act like a cache and creates new object when no matching object is found.
  • The Flyweight objects we create as immutable. This means that they cannot be modified once they have been constructed. Making flyweight objects as immutable helps while sharing them with other objects. 
  • The data structures for graphical representation of characters in a Word Processor is a very good classical example of Flyweight pattern.
  • The String Interning is another very good example of Flyweight pattern.
  • The Flyweight pattern helps us avoiding having large number of objects and allow us to effectively used the created objects by reusing them as much as possible.
  • The Flyweight object essentially has two different kind of attributes – 
    • Intrinsic - An intrinsic (invariant) state attribute is stored and shared in the flyweight object. It is independent of flyweight’s context. So, as the best practice we should make intrinsic states immutable.
    • Extrinsic - An extrinsic (variant) state attribute does not store and share in the flyweight object because it depends on flyweight’s context and varies as context change. Generally, we store and maintain the extrinsic state in the Client objects. We need to pass this extrinsic state to the flyweight object for object creation and processing.

Builder Design Pattern In Java

Here I am with my another article on design patterns - Builder Design Pattern. A very useful creational design pattern that lets us construct complex objects step by step.

Builder Design Pattern

  • The Builder design pattern is designed to provide a flexible solution to various object creation problems in object-oriented programming.
  • The Builder design pattern provides a way to separate the construction of a complex object from its representation.
  • The Builder pattern constructs a complex object by using simple objects and step by step approach.
  •  The pattern provides one of the best ways to create a complex object.
  •  It is one of the Gang of Four design patterns that describe how to solve recurring design problems in object-oriented software.
  • This pattern is useful to build different immutable objects using same object building process.

The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.

Memento Design Pattern In Java

Today, I would like to discuss another behavioral design pattern called the Memento Design Pattern which is used to restore the state of an object to a previous state.

Memento Design Pattern

  • The Memento Design Pattern is one of the twenty-three well-known GoF design patterns that provide the ability to restore an object to its previous state.
  • The Memento Design Pattern is implemented with the help of three objects: the originator, a caretaker, and a memento
    • Originator — The object whose internal state we like to store. The Originator object creates a memento object to store its internal state. So, the Originator object knows how to save and restore itself. The object which gets and sets the values of Memento objects.
    • Caretaker — The object which knows why and when the Originator needs to save and restore itself. The object operates on the Originator while having the possibility to rollback. It maintains the history of the Memento objects created. The caretaker takes a snapshot of Originator before operating.
    • Memento — The POJO object that contains basic state storage and retrieval capabilities.  The Memento object is immutable in general. The object holds the internal state of the Originator and allows it to restore it.
  • The classic example of the Memento Pattern is a pseudorandom number generator or finite state machine.
  • Git stashing is another example of the Momento Design Pattern.
  • The internal state of the Originator object should be saved externally so that the object can be restored to this state later. Also, the object's encapsulation must not be violated.
  •  The caretaker requests a Momento from Originator before operating. And use that Momento to restore the Originator to its previous state if needed.
  • We can make Memento Design Pattern implementation more generic by using Serialization; that will eliminate the requirement of every class having its own Momento class.
  • The Memento Design Pattern can also be used with the Command Design Pattern for achieving undo of the commands.

mementodesign

To understand the Memento Design Pattern let's take the example of the Employee class storing and retrieving its state using EmployeeMemento class.

Observer Design Pattern In Java

Today, I will discuss simple and very useful behavioral design pattern called — Observer Design Pattern. This design pattern is useful when we want get notified about changes in the object state.

Observer Design Pattern

  • The Observer Design Pattern maintains one-to-many dependency between Subject (Observable) and its dependents (Observer) in such a way that whenever state of Subject changes, its dependents get notified.
  • The Observer Design Pattern is a design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. 
  • The Observer Design Pattern is used when we like to have notification upon changes in the objects state.
  • The Observer Design Pattern is one of twenty-three well known Gang of Four design patterns that defines an one-to-many dependency objects so that when one object changes state, all of its dependents get notified and updated automatically.
  • The Observer Design Pattern is mainly used to implement distributed event handling , in "event driven" system.
  • In such systems, the subject is usually called a "source of events", while the observers are called "sink of events".
  • Most modern languages have built-in "event" constructs which implement the observer pattern components.
  • Java also offers Observer and Observable to support built-in event constructs for implementing observer pattern. These are available since Java 1. 
  • But, in Java 9 these are declared deprecated/obsolete because the event model supported by Observer and Observable is quite limited, the order of notifications delivered by Observable is unspecified, and state changes are not in one-for-one correspondence with notifications. For a richer event model, consider using the java.beans package. For reliable and ordered messaging among threads, consider using one of the concurrent data structures in the java.util.concurrent package. For reactive streams style programming, see the Flow API.  (read more on Deprecate Observer and Observable).  

observer design pattern

Iterator Design Pattern In Java

Today, I will discuss a relatively simple and very commonly used behavioral design pattern called — Iterator Design Pattern. Iterator Pattern provides a simple way to iterate through the collection of objects.

Iterator Design Pattern

  • The Iterator Design Pattern is one of twenty-three well known GoF design patterns  provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. 
  • Iterator Design Pattern provides an Iterator object to traverse a collection/container and access its member objects.
  • Iterator Design Pattern is a relatively simple design pattern, which we use almost in every project.
  • Few container requires an algorithm to access the member elements. Iterator Design Pattern decouples any such algorithm from the container.
  • The algorithm can be written separately to use by the Iterator and hence can be use by any container which supports that kind of Iterator object.
  • The Iterator Design Pattern provides flexible and reusable solution of traversing member objects of a container/collection. That make our collection object easier to implement, change, test and reuse.
  • Iterator object also facilitate removing of member object while traversing the collection. So, it's one of the solution of ConcurrentModificationException.

iterator design pattern

Composite Design Pattern in Java

Here I am with another useful design pattern for you — the composite design pattern. I will try to point out the key features to remember while implementing the composite pattern for you.

Composite Design Pattern

The composite pattern is meant to "compose objects into a tree structure to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly"