Search This Blog

Tuesday 17 January 2017

Object Relational Mapping

Object Relational Mapping (ORM) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages.
In object-oriented programming, data-management tasks act on object-oriented (OO) objects that are almost always non-scalar values.
For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain "PhoneNumber objects" and so on. The address-book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.
However, many popular database products such as SQL database management systems (DBMS) can only store and manipulate scalar values such as integers and strings organized within tables. The programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping implements the first approach.
The heart of the problem involves translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.

Persistence

ORM is concerned with helping your application to achieve persistence.
Persistence means that we would like our application’s data to outlive the applications process. In Java terms, we would like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later.

Relational Databases

Specifically, ORM is concerned with data persistence as it applies to relational databases (RDBMS). RDBMS is a very popular persistence mechanism.

The Object-Relational Impedance Mismatch

'Object-Relational Impedance Mismatch' (sometimes called the 'paradigm mismatch') is a way of saying that object models and relational models do not work very well together. RDBMSs represent data in a tabular format, whereas object-oriented languages, such as Java, represent it as objects. Loading and storing objects using a tabular relational database exposes us to 5 mismatch problems…​

Granularity

Sometimes you will have an object model which has more classes than the number of corresponding tables in the database, we says the object model is more granular than the relational model.

Subtypes (Inheritance)

Inheritance is a natural paradigm in object-oriented programming languages. However, RDBMSs do not define anything similar on the whole.

Identity

A RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity a==b and object equality a.equals(b).

Associations

Associations are represented as unidirectional references in Object Oriented languages whereas RDBMSs use the notion of foreign keys. If you need bidirectional relationships in Java, you must define the association twice.
Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.

Data navigation

The way you access data in Java is fundamentally different than the way you do it in a relational database. In Java, you navigate from one association to another walking the object network.

This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.

Object-relational mapping

Object-relational mapping


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






Friday 6 January 2017

Differences between Java EE and Java SE

Java technology is both a programming language and a platform. The Java programming language is a high-level object-oriented language that has a particular syntax and style. A Java platform is an environment in which Java programming language applications run.

The Java Programming Language Platforms
There are four platforms of the Java programming language:
·         Java Platform, Standard Edition (Java SE)
·         Java Platform, Enterprise Edition (Java EE)
·         Java Platform, Micro Edition (Java ME)
·         JavaFX

All Java platforms consist of a Java Virtual Machine (JVM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular platform, that is used to run Java applications. An API is like a library that is used to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language.

Java SE
Java SE's API provides the core functionality of the Java programming language. Java SE defines the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.
In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE
The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME
The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.

JavaFX
JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

Java Programming Language Platforms
Java Programming Language Platforms