design patterns used in core java (j2se) source code

These are some of the design patterns used in core java API that I have gone through in my experience:

Decorator and Bridge patterns – java.io

Observer pattern is available as standard API

Iterator Pattern – All collection classes

Template Pattern – Arrays.sort() and Collection.sort()

Singleton Pattern – Runtime, Calendar

Factory Pattern – Wrappers of primitive data type’s valueOf methods [Integer.valueOf()]

Other most commonly used patterns:
Decorator: Java IO
Strategy Pattern: If you’ve ever used dependency injection, you’ve used the strategy pattern.
Facade: Any service APIs implement this pattern.
Singleton: Used in caching
Builder: While Writing Unit Tests
Prototype: Cloning
Adapter: asList , toString
Chain Of Responsibility: Logging
Factory: Action Mapping
MVC: Web frameworks
Proxy: Web services
Template

difference between design pattern and framework

Framework is a skeleton of code for developing java applications. Design pattern is a solution for a particular problem. The relationship is ‘Framework is made using one or more design patterns’

For example: Struts and Spring are frameworks developed by making use of MVC pattern.

core design principles

 

 MUST REMEMBER 4 ALL PROGRAMMERS 

– Encapsulate what varies

– Favor composition over inheritance

– Program to an interface, not implementations

– Strive for loosely coupled designs between objects that interact (Observer)

– Classes should be open for extension and closed for modification (Decorator)

– Dependency Inversion Principle: Depend on abstraction. Do not depend on concrete classes. This principle suggests that our high level components should not depend on low level components instead both should depend on abstractions. (Command Pattern)

– Principle of least knowledge: Only talk to your friends (Façade Pattern)

– Hollywood Principle: Don’t call us, we will call you. (Template, Factory Method, Observer Patterns)

– A class should have only one reason to change (Iterator Pattern, State Pattern)

core design pattern definitions

must for a programmer or designer

Strategy Pattern
This pattern lets you define a family of algorithms, encapsulate each one and makes them interchangeable
Favor composition over inheritance.

Observer Pattern
It defines one to many dependency between the objects so that when one object changes its state, all its dependents are notified and updated automatically

Decorator Pattern
It attaches additional responsibilities to an object dynamically at runtime. Decorators provide flexible alternative to sub-classing for extending functionality.
Note: Decorators should implement the same interface or abstract class as that of the component they are going to decorate.

Factory Method Pattern
It defines an interface for creating and object and lets subclasses decide which class to instantiate. Few guide lines to follow this pattern:
– No variable should hold a reference to the concrete class
– No class should be derived from concrete class
– No method should over-ride and implemented method of the base class

Singleton Pattern
Ensure a class has only one instance and provide a global point of access to it.

Command Pattern
It allows you to decouple the requestor of an action from the object that actually performs an action.

Adapter Pattern
It converts interface of a class into another interface the clients expect. It lets the classes work together that wouldn’t be otherwise possible because of incompatible interfaces.

Iterator Pattern
It provides a way to access the elements of an aggregate object sequentially without exposing its underlying implementation. It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface.

Composite Pattern
It helps us to compose objects into tree structures to represent part whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Façade Pattern
It provides a unified interface to a set of interfaces in a sub system. Façade defines high level interface that makes the subsystem easier to use.
Note: Actually speaking one should invoke methods that belong to:

  1. Object itself
  2. Objects passed in as a parameter to the method
  3. Any object the method instantiates
  4. Any components of the object (other object references)

Note: Adaptors and Facades may wrap multiple classes but façade’s intent is to simplify while adaptor’s is to convert the interface to something different

Template Pattern
It defines steps of an algorithm and allow subclasses to provide implementation for one or more steps.
Note: It is a great design tool for creating frameworks where framework controls how something gets done but leaves you to specify what is actually happening at each step of an algorithm. Eg: Array.sort(Obj) imples that Obj should impl Comparable interface.

State Pattern
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Proxy Pattern
It provides and place holder for another object to control access to it.

All possible ways of implementing singleton pattern and its pros and cons

Here 5 possible ways are discussed
#1

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static Singleton getInstance() {
 if(instance == null) {
 instance = new Singleton();
 }
 return instance;
 }
}

Cons:
Will not suffice for multi threaded environment

#2

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static synchronized Singleton getInstance() {
 if(instance == null) {
 instance = new Singleton();
 }
 return instance;
 }
}

pros:
Will work in single and multithreaded env’s
Cons:
Will be uneccessary overhead once after instance is created for the first time because every time we call getInstance() method we need to acquire lock and release lock which is overhead after instance is available

#3

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static Singleton getInstance() {
 synchronized(this) {
 if(instance == null) {
 instance = new Singleton();
 }
 }
 return instance;
 }
}

pros:
Will not suffice in multithreaded env’s
Cons:
1. Will be uneccessary overhead once after instance is created for the first time because every time we call getInstance() method we need to acquire lock and release lock which is overhead after instance is available
2. There is a chance of more than one thread getting into if(instance == null) block there by creating multiple instances.

#4 (Double Checking)

public class Singleton {
 private static Singleton instance;

private Singleton() {
 }

public static Singleton getInstance() {
 if(instance == null) {
 synchronized(this) {
 if(instance == null) {
 instance = new Singleton();
 }
 }
 }
 return instance;
 }
}

pros:
Will work in multithreaded env’s
Cons:
1. It will not work in prior versions of JDK5.0
2. Double checking is verey pathetic way of implementing Singleton pattern and best practices doesnt suggest to go for this implementation.

#5

public class Singleton {
 private static Singleton instance = new Singleton();

private Singleton() {
 }

public static Singleton getInstance() {
 return instance;
 }
}

pros:
1. Simplest and trusted way as we are leaving the instantiation to the JVM
2. Works in both single and multithreaded env’s

Using the CSS float Property to Design Web Page Layouts

The CSS float property is a very important property for layout. It allows you to position your Web page designs exactly as you want them to display – but in order to use it you have to understand how it works.

A CSS float property looks like this:

.right {float: right;}

What Floats?

You can’t float every element on a Web page. To get technical, you can only float block-level elements. These are the elements that take up a block of space on the page, like images (<img/>), paragraphs (<p></p>), divisions (<div></div>), and lists (<ul></ul>). Other elements that affect text, but don’t create a box on the page are called inline elements and can’t be floated. These are elements like span (<span></span>), line breaks (<br/>), strong emphasis (<strong></strong>), or italics (<i></i>).
Where Do They Float?
You can float elements to the right or the left. Any element that follows the floated element will flow around the floated element on the other side.

For example, if I float an image to the left, any text or other elements following it will flow around it to the right. See the example. And if I float an image to the right, any text or other elements following it will flow around it to the left. See the example. An image that is placed in a block of text without any float style applied to it will display as the browser is set to display images. This is usually with the first line of following text displayed at the bottom of the image. See the example.
How Far Will They Float?

An element that has been floated will move as far to the left or right of the container element as it can. This results in several different situations depending upon how your code is written. For these examples, I will be floating a small <div> to the left:

  • If the floated element does not have a pre-defined width, it will take up as much horizontal space as required and available, regardless of the float. Note: some browsers attempt to place elements beside floated elements when the width isn’t defined – usually giving the non-floated element only a small amount of space. So you should always define a width on floated elements.
  • If the container element is the HTML <body>, the floated div will sit on the left margin of the page.
  • If the container element is itself contained by something else, the floated div will sit on the left margin of the container.
  • You can nest floated elements, and that can result in the float ending up in a surprising place. For example, this float is a left floated div inside a right floated div.
  • Floated elements will sit next to each other if there is room in the container. For example, this container has 3 100px wide divs floated in a 400px wide container.

You can even use floats to create a photo gallery layout. You put each thumbnail (it works best when they are all the same size) in a DIV with the caption and the float the divs in the container. No matter how wide the browser window is, the thumbnails will line up uniformly.
Turning Off the Float

Once you know how to get an element to float, it’s important to know how to turn off the float. You turn off the float with the CSS clear property. You can clear left floats, right floats or both:

clear: left;
 clear: right;
 clear: both;

Any element that you set the clear property for will appear below an element that is floated that direction. For example, in this example the first two paragraphs of text are not cleared, but the third is.

Play with the clear value of different elements in your documents to get different layout effects. One of the most interesting floated layouts is a series of images down the right or left column next to paragraphs of text. Even if the text is not long enough to scroll past the image, you can use the clear on all the images to make sure that they appear in the column rather than next to the previous image.

Images floated to the left and to the right.

The HTML (repeat this paragraph):

<p> <img src="maliwithcar_tn.jpg" alt="Mali with car" /> Duis aute irure dolor sed do eiusmod tempor incididunt in reprehenderit in voluptate. Cupidatat non proident, ut labore et dolore magna aliqua. </p>

//The CSS (to float the images to the left):

img.float { float:left;clear:left; margin:5px;}

//And to the right:

img.float { float:right;clear:right; margin:5px;}

Using Floats for Layout

Once you understand how the float property works, you can start using it to lay out your Web pages. These are the steps I take to create a floated Web page:

* Design the layout (on paper or in a graphics tool or in my head).
* Determine where the site divisions are going to be.
* Determine the widths of the various containers and the elements within them.
* Float everything. Even the outermost container element is floated to the left so that I know where it will be in relation to the browser view port.

As long as you know the widths (percentages are fine) of your layout sections, you can use the float property to put them where they belong on the page. And the nice thing is, you don’t have to worry as much about the box model being different for IE or Firefox.

Note: this is a very good article I have copied from http://webdesign.about.com/od/advancedcss/a/aa010107.htm

Why would one need try-finally block combination

If we dont wanna handle the exception and instead propogate it up the hierarchy then we go for try-finally combination

how does polymorphism works within the constructors

First of all it is not good practice to call any instance methods inside the constructor, if we cannot avoid then do as little as possible.

What happens:

Assume we call a over-ridden method within the constructor and if that method manipulates data that has not been initialized (because constructor is not yet completed) yet then it will lead to disaster.

The only safe methods inside the constructor to call are final methods in base class.

How does DriverManager identify the type of driver loaded into JVM

Typical JDBC code to connect to the database is:

New Changes in JDK7

JDK7 is packaged with these new changes
– Small language changes
– NIO-2 Enhanced NIO
– invokedynamic
– other features

Small language Changes:

  • Now integer can accept binary format (along with octal and hexadecimal values)
<pre>int i = 0b10110
  • Switch statement can accept string variables. Since String object in Java is considered immutable, java community has come up with this concept

usage:

public int useSwitch(String strCase) {
switch(strCase) {
case "A":
return 1;
case "B":
return 2;
...
default:
return 10;
}
}
  • Inferring types with <>: while using generics RHS of stmt can be replaced with just <>

usage:

</pre>
List<String> list = new ArrayList<>();
<pre>

Note: No need to explicitly mentioned type on the RHS

  • Easy rethrow (replace multiple catch blocks with single catch block)

usage:

try {
// Reflective operations calling Class.forName,
// Class.newInstance, Class.getMethod,
// Method.invoke, etc.
...
} catch(final FileNotFoundException |
SQLException |
ClassNotFoundException) {
log(e);
throw e;
}

// try with resources
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(ds)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}

NIO-2 Enhanced NIO
NIO-2 (Enhanced Asynchronous NIO)

invokedynamic
Dynamic linking of method by the JVM is introduced

Other Features:
Fork joins (for recursive functionalities) – Multi process environment