Search This Blog

Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Sunday 15 January 2017

Singleton Design Pattern in Java

Singleton Design Pattern in Java
Intent
Ensure a class only has one instance, and provide a global point of access to it.

Motivation
It's important for some classes to have exactly one instance.
There are some instances in the application where we have to use just one instance of a particular class
A very simple example is Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
Singleton pattern is used for logging, drivers objects, caching and thread pool.

Applicability
Use the Singleton pattern when
·         There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
·         When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Consequences
The Singleton pattern has several benefits:
1. Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it.
2. Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.
3. Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.
4. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change.

How do we ensure that a class has only one instance and that the instance is easily accessible?
·         A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects.
·         A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created, and it can provide a way to access the instance.

Creating Singleton design pattern
To create the singleton class, we need to have static member of class, private constructor and static factory method.

  • Static member: It gets memory only once because it is static, and the only instance of the Singleton class.
  • Private constructor: It will prevent the instantiation of the Singleton class from outside the class.
  • Static factory method: It will provide the global point of access to the Singleton object and returns the instance to the caller.
Implementation

package com.jasdhir.blog.single;

public class SingletonObject {
      //create an object of SingletonObject class
         private static SingletonObject single = new SingletonObject();

         //make the constructor private so that this class cannot be instantiated
         private SingletonObject(){}

         //Get the only object available
         public static SingletonObject getInstance(){
            return single;
         }
}

package com.jasdhir.blog.single;

public class Main {
public static void main(String[] args) {
      SingletonObject Obj1=SingletonObject.getInstance();
      System.out.println("Object 01 : "+Obj1);
     
      SingletonObject Obj2=SingletonObject.getInstance();
      System.out.println("Object 02 : "+Obj2);
}
}

Output :
Object 01 : com.jasdhir.blog.single.SingletonObject@6d06d69c
Object 02 : com.jasdhir.blog.single.SingletonObject@6d06d69c

Both the objects Obj1 and Obj2 are referring to same instance

Wednesday 11 January 2017

Design Patterns by Type

Let us try to understand Design Patterns by Type
Creational Patterns
Creational patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case.
  • Abstract Factory Pattern : The abstract factory pattern provides a way for creating families of related or dependent objects without specifying their concrete classes.
  • Builder pattern Separate the construction of a complex object from its representation so that the same construction process can create different representations
  • Factory Method Pattern Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses.
  • Prototype Pattern creates objects by cloning an existing object. Create new objects by copying this prototype.
  • Singleton Pattern restricts object creation for a class to only one instance. Ensure a class has only one instance, and provide a global point of access to it.
Structural Patterns
Structural Design Patterns are Design Patterns that ease the design by identifying a simple way to realize relationships between entities. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.
  • Adapter Pattern allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
  • Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently.
  • Composite Pattern composes zero-or-more similar objects so that they can be manipulated as one object.
  • Decorator Pattern dynamically adds/overrides behaviour in an existing method of an object.
  • Facade Pattern provides a simplified interface to a large body of code.
  • Flyweight Pattern reduces the cost of creating and manipulating a large number of similar objects.
  • Proxy Pattern provides a placeholder for another object to control access, reduce cost, and reduce complexity.
 Behavioral Pattern
These design patterns are specifically concerned with communication between objects
  • Chain of responsibility Pattern delegates commands to a chain of processing objects.
  • Command Pattern  creates objects which encapsulate actions and parameters.
  • Interpreter Pattern  implements a specialized language.
  • Iterator Pattern  accesses the elements of an object sequentially without exposing its underlying representation.
  • Mediator Pattern  allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
  • Memento Pattern  provides the ability to restore an object to its previous state (undo).
  • Observer Pattern  is a publish/subscribe pattern which allows a number of observer objects to see an event.
  • State Pattern  allows an object to alter its behavior when its internal state changes.
  • Strategy Pattern  allows one of a family of algorithms to be selected on-the-fly at runtime.
  • Template Pattern  method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
  • Visitor Pattern  separates an algorithm from an object structure by moving the hierarchy of methods into one object.
Design Pattern By Types
Design Patterns By Types

Tuesday 10 January 2017

What is a Design Pattern?

Christopher Alexander  says, "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice"

A pattern has four essential elements:
  •  Pattern Name : is used to describe a design problem, its solutions, and consequences in a word or two. Naming a pattern increases our design vocabulary. It makes it easier to think about designs and convey them to others.
  • Problem : describes when to apply the pattern. It explains the problem and its context. It might describe specific design problems.
  • Solution : describes the elements that make up the design, their relationships, responsibilities, and collaborations. The solution doesn't describe a particular concrete design or implementation, since a pattern is like a template which can be applied in many different situations.
  •  Consequences : are the results and trade-offs of applying the pattern.



A design pattern names, abstracts, and identifies the key aspects of a common design structure that make it useful for creating a reusable object-oriented design.
The design pattern identifies the participating classes and instances, their roles and collaborations, and the distribution of responsibilities.
Each design pattern focuses on a particular object-oriented design problem or issue.

Organizing Design Patterns
Design patterns vary in their granularity and level of abstraction. Because there are many design patterns, we need a way to organize them.
The classification helps us learn the patterns faster.


We classify design patterns by two criteria.

1.    Purpose : reflects what a pattern does. 

Patterns can have either creational, structural, or behavioral purpose. Creational patterns concern the process of object creation. 

Structural patterns deal with the composition of classes or objects. 

Behavioral patterns characterize the ways in which classes or objects interact and distribute responsibility.


2.     Scope :  specifies whether the pattern applies primarily to classes or to objects. 

Class patterns deal with relationships between classes and their subclasses. These relationships are established through Inheritance, so they are static—fixed at compile-time. 

Object patterns deal with object relationships, which can be changed at run-time and are more dynamic.




Design Pattern
Design Pattern






Monday 5 December 2016

What is MVC architecture in J2EE

MVC stands for Model-View-Controller architecture. It promotes loose coupling between components by separating the functionality of displaying and maintaining of the data. It is often used by applications that need the ability to maintain multiple views like HTML, WML, Swing, XML based Web service etc. Multiple views and controllers can interface with the same model. Even new types of views and controllers can interface with a model without forcing a change in the model design.

To summarize the MVC does the following
  • Separation of Model from View components makes it possible to implement several user interfaces that reuse the common core business logic.
  • Duplication of low-level Model code is eliminated across multiple UI implementations.
  • Decoupling of Model and View code results in an improved ability to write unit tests for the core business logic code.
  • Modularity of components allows core logic developers and UI developers to work simultaneously without affecting the other.

  
A model represents the core business logic and state. A model commonly also maps to data the database and will also contain core business logic.
  • Manages the app data and state
  • Not concerned with UI or presentation
  • Often persists somewhere
  • Same model should be reusable, unchanged in different interfaces

  
A view renders the contents of a model. A view accesses the data from the model and adds display logic to present the data. 
  • Present the Model to the user in an appropriate interface
  • Allows user to manipulate data
  • Does not store any data.
  • Easily reusable & configurable to display different data


A controller acts as the glue between a model and a view. A controller translates interactions with the view into actions to be performed by the model. User interactions in a Web application appear as GET and POST HTTP  requests. The actions performed by a model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.
  • Intermediary between Model & View
  • Updates the view when the model changes
  • Updates the model when the user manipulates the view
MVC pattern decouples how data is manipulated from how data is displayed or stored. MVC is a way of developing apps by keeping the data (model) used in the program, and the visual (view) component separate from one another, each interacting only with a controller containing the logic. The view and the model interact only with the controller NEVER with each other.
MVC
MVC