Using SimpleDateFormat to convert a date in string into a desired format
SimpleDateFormat sdfYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd"); // The input date string will be in yyyy-MM-dd format
SimpleDateFormat sdfDDMMMYYYY = new SimpleDateFormat("dd-MMM-yyyy"); //The output date string will be in dd-MMM-yyyy format
Date date;
try {
date = sdfYYYYMMDD.parse("2012-12-09"); // Parse the input string into a date object. parse method throws a ParseException
System.out.println(date); // Prints as Sun Dec 09 00:00:00 IST 2012
String formattedDate = sdfDDMMMYYYY.format(date); // Format the date object to a string in the dd-MMM-yyyy (desired format).
System.out.println(formattedDate); // Prints as 09-Dez-2012
} catch (ParseException e) {
e.printStackTrace();
}
If we need to use sorting on dates, say for using Collections.sort(list), we implement Comparable interface and override the compareTo() method.
@Override
public int compareTo(EmpTable o) {
String dateinstr1 = this.getDate();
String dateinstr2 = o.getDate();
try{
SimpleDateFormat sdfyyyymmdd = new SimpleDateFormat("dd-MMM-yyyy");
Date date1 = sdfyyyymmdd.parse(dateinstr1);
Date date2 = sdfyyyymmdd.parse(dateinstr2);
return date1.compareTo(date2);
}catch(ParseException e){
e.printStackTrace();
}
return 0;
}
If dates are as Date objects, the above piece of code can be used for displaying dates in ascending format.
If they need to be in descending format, the highlighted text above needs to be written as
return - date1.compareTo(date2);
i.e., prefix with a minus sign.
Monday, April 4, 2016
Thursday, March 24, 2016
Design Pattern - 7 Adapter and Facade Pattern
Giving a slip to Design pattern 6, the command pattern
Adapter pattern - Converts the interface of a class into another interface clients expect. Lets classes work together that couldn't otherwise because of incompatible interfaces.
Facade pattern - Provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.
Adapter pattern - Typical example is using a adapter class to adapt a Enumeration class of Java to that of Iterator class.
Adapter pattern has three interfaces -
- The Target interface
- The Adapter interface
- The Adaptee interface
Example: Lets have a Duck interface
interface Duck{
void quack();
void fly();
}
interface Turkey {
void gobble();
void shortFly();
}
class DuckAdapter implements Duck{
Turkey turkey;
DuckAdapter(Turkey turkey){
this.turkey = turkey;
}
void quack(){
turkey.gobble();
}
void fly(){
turkey.shortFly();
}
}
In the above example, the DuckAdapter adapts to the Turkey(Adaptee). The client is not aware that the turkey's methods are getting executed.
Adapter Patterns are of two forms - Class Adapters and Object Adapter. Class Adapter require multiple inheritance.
Facade Pattern - Provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. A facade decouples a client from a complex subsystem.
For example, taking the example of home theatre system. It comprises of many subsystems such as a projector system, sound system, etcetra. If we were to do a simple job of watching a movie using the dvd player, and we take the subsystems into account, we end up creating multiple classes in a single class. Implementing Facade requires we compose the facade with its subsystem and use delegation to perform the work of the facade.
Use an Adapter, when you need to use an existing class and its interface is not the one you need.
Use a facade, when you need to simplify and unify a large interface or complex set of interfaces.
Adapter pattern - Converts the interface of a class into another interface clients expect. Lets classes work together that couldn't otherwise because of incompatible interfaces.
Facade pattern - Provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.
Adapter pattern - Typical example is using a adapter class to adapt a Enumeration class of Java to that of Iterator class.
Adapter pattern has three interfaces -
- The Target interface
- The Adapter interface
- The Adaptee interface
Example: Lets have a Duck interface
interface Duck{
void quack();
void fly();
}
interface Turkey {
void gobble();
void shortFly();
}
class DuckAdapter implements Duck{
Turkey turkey;
DuckAdapter(Turkey turkey){
this.turkey = turkey;
}
void quack(){
turkey.gobble();
}
void fly(){
turkey.shortFly();
}
}
In the above example, the DuckAdapter adapts to the Turkey(Adaptee). The client is not aware that the turkey's methods are getting executed.
Adapter Patterns are of two forms - Class Adapters and Object Adapter. Class Adapter require multiple inheritance.
Facade Pattern - Provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. A facade decouples a client from a complex subsystem.
For example, taking the example of home theatre system. It comprises of many subsystems such as a projector system, sound system, etcetra. If we were to do a simple job of watching a movie using the dvd player, and we take the subsystems into account, we end up creating multiple classes in a single class. Implementing Facade requires we compose the facade with its subsystem and use delegation to perform the work of the facade.
Use an Adapter, when you need to use an existing class and its interface is not the one you need.
Use a facade, when you need to simplify and unify a large interface or complex set of interfaces.
Tuesday, March 22, 2016
How to create a JPA project in RAD
The tutorials at the below link had excellent tutorial to create a JPA project in RAD. Useful to create in Eclipse as well.
http://www.ibm.com/support/knowledgecenter/SSRTLW_8.0.4/com.ibm.rad.samptut.doc/tutorials/javaee/topics/jpa_create_abst.html
http://www.ibm.com/support/knowledgecenter/SSRTLW_8.0.4/com.ibm.rad.samptut.doc/tutorials/javaee/topics/jpa_create_abst.html
Friday, March 18, 2016
Design Pattern - 5 Singleton Pattern.
One of the simplest patterns - Singleton patterns - Ensures a class has only one instance and provides gloabl access to it.
Steps:
Method 1:
1) Create a private constructor.
2) Create a static class variable.
3) Create a public method to return an object of the class.
Class A{
private static A singleinstance;
private A() {}
public static A getInstance() {
if(singleinstance==null) { //lazy initialization
singleinstance = new A();
}
return singleinstance;
}
}
Method 2:
Class A{
private static A singleinstance= new A();
private A() {}
public static A getInstance() { // Eager initialization
return singleinstance;
}
}
Method 3: To avoid synchronization issues while multithreading,
Class A{
private static A singleinstance= new A();
private A() {}
public static synchronized A getInstance() { // Ensures only one instance is created while multi threading
if(singleinstance==null) {
singleinstance = new A();
}
return singleinstance;
}
}
Method 4: Double checked locking -
Using synchronized keyword over a method is a performance overhead. So,
Class A{
private static A singleinstance;
private A() {}
public static A getInstance() { // Ensures only one instance is created while multi threading
if(singleinstance==null) {
synchronized(this){
if(singleinstance==null){
singleinstance = new A();
}
}
return singleinstance;
}
}
Only for the first time, only then an entry to synchronized block is made.
So, in stead of Method 3, the above approach can be followed in case of multiple threads are used. This way, performance overhead issue can be resolved.
Design Principles so far:
1) Encapsulate what varies
2) Favor composition over inheritance.
3) Program to interfaces, not implementations.
4) Strive for loosely coupled designs between objects that interact.
5) Classes should be open for extension, but closed for modification.
6) Depend on abstractions. Do not depend on concrete classes.
Used: Logging, Preferences and Registry settings, Thread pools, caches, dialog boxes.
Thursday, March 17, 2016
Design Pattern - 4 Factory Pattern.
The Factory Design Pattern - Defines and interface for creating an object, but lets subclasses decide which class to instantiate. Factory pattern lets a class defer instantiation to subclasses.
This pattern gives a way to encapsulate the instantiations of concret types.
Example: Consider a product Pizza. There are different types of pizza.CheesePizza, VegPizza, ChickenPizza. These are subtypes of the product Pizza. Taking Pizza as a class, CheesePizza, VegPizza and ChickenPizza are the sub classes of Pizza.
Now, let's take the case of a PizzaStore where people order pizza. The main objective of a PizzaStore is to cater to customers who order pizzas. People place order and PizzaStore irrespective of whatever pizza was ordered by the customer, need to cater to the customer.
Thus, PizzaStore uses the product Pizza. PizzaStore has operations such as orderPizza. The process of instantiating which type of pizza can be isolated from the PizzaStore.
class VegPizza extends Pizza{
}
abstract class PizzaStore {
factoryMethod();
orderPizza(){ }
}
The factory method can be implemented by classes inherting PizzaStore, such as NewYorkStylePizzaStore or CaliforniaStylePizzaStore, thereby creating NewYorkStyleCheesePizza ot CaliforniaStyleCheesePizza.
Design Principle: Depend upon abstractions. Do not depend upon concrete classes.
Abstract Factory Pattern: Provides an interface for creating families of related or dependant objects without specifying their concrete classes.
Design Principles so far:
1) Encapsulate what varies
2) Favor composition over inheritance.
3) Program to interfaces, not implementations.
4) Strive for loosely coupled designs between objects that interact.
5) Classes should be open for extension, but closed for modification.
6) Depend on abstractions. Do not depend on concrete classes.
This pattern gives a way to encapsulate the instantiations of concret types.
Example: Consider a product Pizza. There are different types of pizza.CheesePizza, VegPizza, ChickenPizza. These are subtypes of the product Pizza. Taking Pizza as a class, CheesePizza, VegPizza and ChickenPizza are the sub classes of Pizza.
Now, let's take the case of a PizzaStore where people order pizza. The main objective of a PizzaStore is to cater to customers who order pizzas. People place order and PizzaStore irrespective of whatever pizza was ordered by the customer, need to cater to the customer.
Thus, PizzaStore uses the product Pizza. PizzaStore has operations such as orderPizza. The process of instantiating which type of pizza can be isolated from the PizzaStore.
class VegPizza extends Pizza{
}
abstract class PizzaStore {
factoryMethod();
orderPizza(){ }
}
The factory method can be implemented by classes inherting PizzaStore, such as NewYorkStylePizzaStore or CaliforniaStylePizzaStore, thereby creating NewYorkStyleCheesePizza ot CaliforniaStyleCheesePizza.
Design Principle: Depend upon abstractions. Do not depend upon concrete classes.
Abstract Factory Pattern: Provides an interface for creating families of related or dependant objects without specifying their concrete classes.
Design Principles so far:
1) Encapsulate what varies
2) Favor composition over inheritance.
3) Program to interfaces, not implementations.
4) Strive for loosely coupled designs between objects that interact.
5) Classes should be open for extension, but closed for modification.
6) Depend on abstractions. Do not depend on concrete classes.
Tuesday, March 15, 2016
Design Pattern - 3 - Decorator Pattern
Decorator Pattern - Attaches additional responsibilities to an object dyanmically.
Decorators provide a flexible alternative to subclassing for extending functionality.
Example: Take the case of veg. pizza being ordered. Customer wants to add extra cheese as topping.
Here the veg. pizza is the basic class and cheese is the decorator class. Cheese class decorates the veg. pizza.
Similarly, if user decides to add some extra jalepenos. Then, jalepeno is a decorator class.
Code:
class VegPizza extends Pizza {
// description of VegPizza
String topping;
addTopping(){
topping = topping+"veg";
}
}
abstract class Toppings extends Pizza {
}
class CheeseTopping extends Toppings {
Pizza pizza;
CheeseTopping(Pizza pizza){
this.pizza= pizza;
}
addTopping(){
pizza.topping=pizza.topping + "cheese";
}
}
class JalepenoTopping extends Toppings {
Pizza pizza;
JalepenoTopping(Pizza pizza){
this.pizza= pizza;
}
addTopping(){
pizza.topping=pizza.topping + "Jalepeno";
}
}
class MainClass{
public static void main(String args[]){
Pizza vegPizza = new VegPizza();
CheeseTopping topping1= new CheeseTopping(vegPizza);
JalepenoTopping topping2 = new JalepenoTopping(vegPizza);
System.out.print("Toppings added:+"vegPizza.toppings);
}
}
Design Principle: Classes should be open for extension, but closed for modification.
Design Principles so far:
1) Encapsulate what varies
2) Favor composition over inheritance.
3) Program to interfaces, not implementations.
4) Strive for loosely coupled designs between objects that interact.
5) Classes should be open for extension, but closed for modification.
The downside of the decorator pattern is - a lot of small classes(decorator) can get added up making it difficult to understand the design.
However, the benefit lies in the fact the the client or the base class not being aware that it is being decorated upon.
Tuesday, March 8, 2016
Design Pattern - 2 Observer Pattern
The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated successfully.
Observer pattern has a Subject to which Observers listen to. It is similar to a subscriber-enewspaper relationship. Whenever a newspaper (subject) is published, the subscribers(observers) are notified.
Also similar like a button in a page whose listeners perform different operations based on the button action.
Design principle: Strive for loosely coupled designs between objects that interact.
Observable is a class in java.util. package where the observer pattern is implemented.
Typically, the Subject interface or Observable class has methods to add an observer, remove an observer and notifyObservers().The subject maintains a list of observers.The subject is unaware when a new observer is added.
public SubjectImpl implements Subject {
private List observerList ;
public void addObserver(Observer observer){ observerList.add(observer); }
public void removeObserver(Observer observer { // code to remove from observerlist; }
public void notifyObservers() { // Iterate over list of observerList and notify the data change }
}
The Observer interface or class implementing observer interface will register or add itself to the Subject. The subject reference is maintained in the observer class.
public ObserverImpl implements Observer{
private Subject subject;
public ObserverImpl(Subject subjectarg){
this.subject = subjectarg;
subject.addObserver(this);
}
}
The order of notification to observers CANNOT be guranteed by subject.
Swing uses heavy usage of Observer pattern.
Design principles so far:
Design Principle 1: Identify the parts of the application that can vary and separate them from what stays the same. Encapsulate what varies.
Design Principle 2: Program to an interface, not an implementation.
Design Principle 3: Favor composition over inheritance.
Design principle 4: Strive for loosely coupled designs between objects that interact.
Observer pattern has a Subject to which Observers listen to. It is similar to a subscriber-enewspaper relationship. Whenever a newspaper (subject) is published, the subscribers(observers) are notified.
Also similar like a button in a page whose listeners perform different operations based on the button action.
Design principle: Strive for loosely coupled designs between objects that interact.
Observable is a class in java.util. package where the observer pattern is implemented.
Typically, the Subject interface or Observable class has methods to add an observer, remove an observer and notifyObservers().The subject maintains a list of observers.The subject is unaware when a new observer is added.
public SubjectImpl implements Subject {
private List observerList ;
public void addObserver(Observer observer){ observerList.add(observer); }
public void removeObserver(Observer observer { // code to remove from observerlist; }
public void notifyObservers() { // Iterate over list of observerList and notify the data change }
}
The Observer interface or class implementing observer interface will register or add itself to the Subject. The subject reference is maintained in the observer class.
public ObserverImpl implements Observer{
private Subject subject;
public ObserverImpl(Subject subjectarg){
this.subject = subjectarg;
subject.addObserver(this);
}
}
The order of notification to observers CANNOT be guranteed by subject.
Swing uses heavy usage of Observer pattern.
Design principles so far:
Design Principle 1: Identify the parts of the application that can vary and separate them from what stays the same. Encapsulate what varies.
Design Principle 2: Program to an interface, not an implementation.
Design Principle 3: Favor composition over inheritance.
Design principle 4: Strive for loosely coupled designs between objects that interact.
Thursday, March 3, 2016
Design Pattern - 1 - Strategy Pattern
Design Principle 1: Identify the parts of the application that can vary and separate them from what stays the same. Encapsulate what varies.
Design Principle 2: Program to an interface, not an implementation.
Design Principle 3: Favor composition over inheritance.
Strategy Pattern: The strategy pattern defines a family of algorithms, encapsulates each one and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Courtesy: Head First Design Patterns
Design Principle 2: Program to an interface, not an implementation.
Design Principle 3: Favor composition over inheritance.
Strategy Pattern: The strategy pattern defines a family of algorithms, encapsulates each one and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Courtesy: Head First Design Patterns
Subscribe to:
Comments (Atom)