Design Pattern | Learn for Master
  • Five ways to implement Singleton pattern in Java

    In this post, I will describe five ways to implement the Singleton pattern in Java. They are Synchronization the getInstane() method,static final variable, using double checking lock with volatile keyword, using SingletonHolder, and Enum.

    1. Classic Java Singleton pattern

    The following code is the simplest implementation of Singleton Pattern in Java. However it is not multiple thread-safe. 

    The singleton pattern implemented in the above example is easy to understand. We maintain a static reference to the singleton instance and returns that reference from the static getInstance() method. We also make the Constructor private,

    [Read More...]
  • Design Pattern: Observer Pattern in Java

    observer pattern

    We use simple examples and diagrams to describe the concept of observer pattern. We also give a simple implementation of the observer pattern in Java. 

    What is Observer Pattern

    The observer pattern defines a one-to-many relationship between two kinds of objects. The one side is called Subject, which maintains a list of Objects (called observers), and automatically notify each of the observers if something interesting happens. 

    The definition of the Observer pattern provided in the GoF book, Design Patterns: Elements of Reusable Object-Oriented Software, is:

    “One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves.

    [Read More...]