Core Java 2
Question 1
How many String objects are created in the following code?
1. String A, B, C;
2. A = “1234”;
3. B = A;
4. C = A + B;
a. 1
b. 2
c. 3
d. 4
Where are they created?
____it will create three string objects _____________________________________________________________
_________________________________________________________________
_________________________________________________________________
Question 2
Which of the following versions of initialising a char variable would cause a compiler error? [Check all correct answers]
a. char c = -1;
b. char c = ‘\u00FF’;
c. char c = (char) 4096;
d. char c = 4096L;
e. char c = ‘c’;
f. char c = “c”;
Question 3
What happens when you try to compile and run the following code?
1. public class EqualsTest {
2. public static void main(String args[]) {
3. Long LA = new Long ( 7 );
4. Long LB = new Long ( 7 );
5. if (LA == LB)
6. System.out.println(“Equal”);
7. else System.out.println(“Not Equal”);
8. }
9. }
a. The program compiles but throws a runtime exception in line 5.
b. The program compiles and prints “Equal”.
c. The program compiles and prints “Not Equal”.
Question 4
What would happen if you tried to compile and run the following code?
1. public class EqualsTest {
2. public static void main(String args[]) {
3. Long L = new Long ( 7 );
4. if (L.equals( 7L ))
System.out.println(“Equal”);
5. else System.out.println(“Not Equal”);
6. }
7. }
a. The program would compile and print “Equal”.
b. The program would compile and print “Not Equal”.
c. The compiler would object to line 4.
d. A runtime cast error would occur at line 4.
Question 5
What would happen if you tried to compile and run the following code?
1. public class EqualsTest {
2. public static void main(String args[]) {
3. Object A = new Long ( 7 );
4. Long L = new Long ( 7 );
5. if (A.equals( L ))
6. System.out.println(“Equal”);
7. else System.out.println(“Not Equal”);
8. }
9. }
a. The program would compile and prints “Equal”.
b. The program would compile and prints “Not Equal”.
c. The compiler would object to line 5.
d. A runtime cast error would occur at line 5.
Question 6
Given the following listing of the Widget class:
1. class Widget extends Thingee {
2. static private int widgetCount = 0;
3. public String wName;
4. int wNumber;
5. static synchronized int addWidget() {
6. widgetCount++;
7. wName = “I am Widget # ” + widgetCount;
8. return widgetCount;
9. }
10. public Widget() {
11. wNumber = addWidget();
12. }
13. }
What happens when you try to compile the class and use multiple Widget objects in a program?
a. The class compiles and each Widget will get a unique wNumber and wName reflecting the order in which the Widgets were created.
b. The compiler objects to line 7.
c. The class compiles, but a runtime error related to the access of the variable wName occurs in the addWidget method.
Question 7
Trying to compile the following source code produces a compiler warning to the effect that the variable tmp may not have been initialized.
1. class Demo {
2. String msg = “Type is ”;
3. public void showType ( int n ) {
4. String tmp;
5. if ( n > 0 ) tmp = “positive”;
6. System.out.println( msg + tmp );
7. }
8. }
Which of the following changes would eliminate this warning? [Check all correct answers]
a. Make line 4 read
4. String tmp = null;
b. Make line 4 read
4. String tmp = “”;
c. Insert a line following line 5
6. else tmp = “not positive”;
d. Remove line 4 and insert a new line after 2 so tmp becomes a member variable instead of a local variable in showType.
3. String tmp;
Question 8
The following method definition is designed to parse and return an integer from an input string that is expected to look like “nnn, ParamName”. In the event of NumberFormatException, the method is to return –1.
1. public int getNum( String S ) {
2. try {
3. String tmp = S.substring( 0, S.indexOf( ‘,’ ));
4. return Integer.parseInt( tmp );
5. } catch ( NumberFormatException e ) {
6. System.out.println( “Problem in ” + tmp );
7. }
8. return –1;
9. }
What happens when you try to compile this code and execute the method with an input string that does not contain a comma separating the number from the text data?
a. A compiler error in line 6 prevents compilation.
b. The method prints the error message to standard output and returns –1.
c. A NumberFormatException is thrown in line 3.
d. A StringIndexOutOfBoundsException is thrown in line 3.
Question 9
Given the following class definition:
1. public class DerivedDemo extends Demo {
2. int M, N, L;
3. public DerivedDemo( int x, int y ) {
4. M = x; N = y;
5. }
6. public DerivedDemo( int x) {
7. super( x );
8. }
9. }
Which of the following constructor signatures must exist in the Demo class for DerivedDemo to compile correctly? [Check all correct answers]
a. public Demo( int a, int b)
b. public Demo( int c)
c. public Demo( )
Question 10
When programming a local inner class inside a method code block, which of the following statements is true?
a. The inner class will have access only to static variables in the enclosing class.
b. The inner class can use any variables declared in the method.
c. The inner class can use only local variables that are declared final.
d. The inner class can use only local variables that are declared static.
Question 11
You have been given the following programming problem with respect to a Java application. An existing class called AB now needs some additional functionality, which it is proposed to add with a nested inner class, ABC. You have been able to establish the following requirements:
1. There will probably be more than one AB instance active in the application, so the solution has to work no matter how many AB instances there are.
2. ABC will need to have access to instance methods and variables as well as static variable.
3. More than one method in AB will have access to a method of ABC.
Which configuration of a nested class is the best bet for this problem?
a. A static class
b. A member inner class
c. An inner class defined in an AB method
d. An anonymous inner class
Question 12
In the following code for a class in which methodA has an inner class, which variables would the statement in line 8 be able to use in place of XX? [Check all correct answers]
1. public class Base {
2. private static final int ID = 3;
3. private String name;
4. public void methodA( final int nn ) {
5. int serialN = 11;
6. class inner {
7. void showResult( ) {
8. System.outprintln( “Rslt = ” + XX );
9. }
10. } // end class inner
11. new inner( ).showResult( );
12. } // end methodA
13. }
a. The int ID in line 2
b. The String in line 3
c. The int nn in line 4
d. The int serialN in line 5
Question 13
What will happen when you try to compile the following code?
1. public void printArray( Object x ) {
2. if ( x instanceof int[ ] ) {
3. int[ ] n = ( int[ ] ) x;
4. for ( int i = 0; i < n.length; i++ ) {
5. System.out.println( “integers = ” +
n[ i ] );}
6. }
7. if ( x instanceof String[ ] ) {
8. System.out.println( “Array of Strings” ;
9. }
10. }
a. It compiles without error.
b. The compiler objects to line 2 comparing an Object with an array.
c. The compiler objects to line 3 casting an Object to an array of int primitives.
d. The compiler objects to line 7 comparing an Object to an array of Objects.
Answer is : System.out.println( “Array of Strings” ;
) excepted
Question 14
Here is the class hierarchy showing the java.awt.event.ActionEvent class family tree:
java.lang.Object
|-- java.util.EventObject
|-- java.awt.AWTEvent
|-- java.awt.event.ActionEvent
Suppose you have the following code to count events and save the most recent event.
1. int evtCt = 0;
2. AWTEvent lastE;
3. public void saveEvent( AWTEvent evt ) {
4. lastE = evt;
5. evtCt++;
6. }
Which of the following calls of saveEvent would run without causing an exception? [Check all correct answers]
a. an AWTEvent object reference
b. an ActionEvent object reference
c. an EventObject object reference
d. null value
Question 15
Suppose you have two classes defined as follows:
class ApBase extends Object implements Runnable
class ApDerived extends ApBase implements Observer
Given two variables created as follows:
ApBase aBase = new ApBase( );
ApDerived aDer = new ApDerived( );
Which of the following Java statements will compile and execute without error? [Check all correct answers]
a. Runnable rn = aDer;
b. Runnable rn2 = (Runnable) aBase;
c. Observer ob = aBase;
d. Observer ob2 = (Observer) aBase;
Question 16
The following method is designed to convert an input string to a floating-point number while detecting a bad format.
1. public boolean strCvt( String s ) {
2. try {
3. factor = Float.valueOf( s ).floatValue( );
4. return true;
5. } catch ( NumberFormatException e ) {
6. System.out.println( “Bad number ” + s );
7. factor = Float.NaN;
8. } finally { System.out.println( “Finally” );
9. }
10. return false;
11. }
Which of the following descriptions of the results of various inputs to the method are correct? [Check all correct answers]
a. Input = “0.234” – Result: factor = 0.234, “Finally” is printed, true is returned.
b. Input = “0.234” – Result: factor = 0.234, “Finally” is printed, false is returned.
c. Input = null – Result: factor = NaN, “Finally” is printed, false is returned.
d. Input = null – Result: factor unchanged, “Finally” is printed, NullPointerException is thrown.
Question 17
Here is the class hierarchy of exceptions related to array index and string index errors:
Exception
+-- RuntimeException
+-- IndexOuOfBoundsException
+-- ArrayIndexOuOfBoundsException
+-- StringIndexOuOfBoundsException
Suppose you had a method X that could throw both array index and string index exceptions. Assuming that X does not have any try-catch statements, which of the following statements are correct? [Check all correct answers]
a. The declaration for X must include “throws ArrayIndexOuOfBoundsException, StringIndexOuOfBoundsException”.
b. If a method calling X catches IndexOuOfBoundsException, both array and string index exceptions will be caught.
c. If the declaration for X includes “throws IndexOuOfBoundsException”, any calling method must use a try catch block.
d. The declaration for X does not have to mention exceptions.
Question 18
You are writing a set of classes related to cooking and have created your own exception hierarchy derived from java.lang.Exception as follows:
Exception
+-- BadTasteException
+-- BitterException
+-- SourException
Your custom exceptions have constructors taking a String parameter. You have a method declared as follows:
int rateFlavor( Ingredient[ ] list ) throws BadTasteException
Which of the following shows a correct complete statement to throw one of your custom exceptions?
a. new SourException( “Ewww!” );
b. throws new SourException( “Ewww!” );
c. throw new SourException( “Ewww!” );
d. throw SourException( “Ewww!” );
Question 19
The GenericFruit class declares the following method:
public void setCalorieContent( float f )
You are writing a class Apple to extend GenericFruit and want to add methods that overload the method in GenericFruit. Which of the following would constitute legal declarations of overloading methods? [Check all correct answers]
a. protected float setCalorieContent( String s )
b. protected void setCalorieContent( float x )
c. public void setCalorieContent( double d )
d. public void setCalorieContent( String s ) throws NumberFormatException
Question 20
The GenericFruit class declares the following method to return a float number of calories in the average serving size:
public float aveCalories( )
Your Apple class, which extends GenericFruit, overrides this method. In a DietSelection class that extends Object, you want to use the GenericFruit method on an Apple object. Select the correct way to finish the statement in the following code fragment so the GenericFruit version of aveCalories is called using the gf reference, or select option d.
1. GenericFruit gf = new Apple( );
2. float cal = // finish this statement using gf
a. gf.aveCalories( );
b. ( ( GenericFruit ) gf ).aveCalories( );
c. gf.super.aveCalories( );
d. There is no way to call the GenericFruit method.
Question 21
The GenericFruit class declares the following method to return a float calculated from a serving size:
protected float calories( float serving )
In writing the Apple class that extends GenericFruit, you propose to declare an overriding method with the same parameter list and return type. Which access modifiers could you use with this overriding method? [Check all correct answers]
a. private
b. protected
c. public
d. “package”; that is, a blank access modifier
Question 22
Which of the following statements about the java.util.Vector and java.util.Hashtable classes are correct? [Check all correct answers]
a. A Vector can hold object references or primitive values.
b. A Vector maintains object references in the order they were added.
c. A Hashtable requires String objects as keys.
d. A Hashtable maintains object references in the order they were added.
e. Both Vector and Hashtable use synchronized methods to avoid problems due to more than one Thread trying to access the same collection.
Question 23
In the following class definitions, which are in separate files, note that the Widget and BigWidget classes are in different packages:
1. package conglomo;
2. public class Widget extends Object {
3. private int myWidth;
4. XXXXXX void setWidth( int n ) {
5. myWidth = n;
6. }
7. }
// the following is in a separate file
8. import conglomo.Widget;
9. public class BigWidget extends Widget {
10. BigWidget( ) {
11. setWidth( 204 );
12. }
13. }
Which of the following modifiers, used in line 4 instead of XXXXXX, would allow the BigWidget class to access the Widget.setWidth method (as in line 11)? [Check all correct answers]
a. private
b. protected
c. blank – that is, the method declaration would read void setWidth( int n )
d. public
Question 24
What happens on trying to compile and run the following code?
1. public class EqualsTest {
2. public static void main( String args[ ] ) {
3. float pear = 0.0F;
4. for(int i = 0; i<10; i++) pear = pear + 0.1F;
5. if (pear == 1.0F)
System.out.println( "Equal" );
6. if (pear != 1.0F)
System.out.println( "Not Equal" );
7. }
8. }
a. The program compiles and prints “Not Equal”.
b. The program compiles and prints “Equal”.
c. The compiler objects to line 3.
d. The compiler objects to using == with primitives in line 5.
Question 25
Given the following method in an application
1. public String setFileType( String fname ) {
2. int p = fname.indexOf( ‘.’ );
3. if( p > 0 ) fname = fname.substring( 0, p );
4. fname += “.txt”;
5. return fname;
6. }
and given that another part of the class has the following code
7. String TheFile = “Program.java”;
8. File F = new File( setFileType( TheFile ) );
9. System.out.println( “Created ” + TheFile );
what will be printed by the statement in line 9?
a. Created Program.java
b. Created Program.txt
c. Created Program.java.txt
Question 26
What happens when this method is called with an input of “Java rules”?
1. public String addOK( String S) {
2. S += “ OK!”;
3. return S;
4. }
a. The method will return “ OK!”;
b. A runtime exception will be thrown.
c. The method will return “Java rules OK!”.
d. The method will return “Java rules”.
Question 27
Which of the following code fragments are legal Java code? [Check all correct answers]
a. String A = “abcdefg”;
A -= “cde”;
b. String A = “abcdefg”;
A += “cde”;
c. Integer J = new Integer( 27 );
J -= 7;
d. Integer J = new Integer( 27 );
J--;
Question 28
Which statements regarding the following method definition are true?
boolean e() {
try {
assert false;
} catch (AssertionError ae) {
return true;
}
return false; // (1)
}
The code will fail to compile since catching AssertionError is illegal
The code will fail to compile since the return statement at (1) is unreachable
The method will return true under all circumstances
The method will return false under all circumstances
The method will return true if and only if assertions are enabled at runtime
Question 29
Which of the following statements are true?
The instanceof operator can be used to determine if a reference is an instance of a class, but not an interface.
transient and volatile are Java modifiers.
Constructors are not inherited.
A static method may not be overriden to be non-static.
The size of a string can be retrieved using the length property.
Question 30
What will be written to the standard output when the following program is run?
class Base {
int i;
Base() { add(1); }
void add(int v) { i += v; }
void print() { System.out.println(i); }
}
class Extension extends Base {
Extension() { add(2); }
void add(int v) { i += v*2; }
}
public class Qd073 {
public static void main(String[] args) {
bogo(new Extension());
}
static void bogo(Base b) {
b.add(8);
b.print();
}
}
9
18
20
21
22
How many String objects are created in the following code?
1. String A, B, C;
2. A = “1234”;
3. B = A;
4. C = A + B;
a. 1
b. 2
c. 3
d. 4
Where are they created?
____it will create three string objects _____________________________________________________________
_________________________________________________________________
_________________________________________________________________
Question 2
Which of the following versions of initialising a char variable would cause a compiler error? [Check all correct answers]
a. char c = -1;
b. char c = ‘\u00FF’;
c. char c = (char) 4096;
d. char c = 4096L;
e. char c = ‘c’;
f. char c = “c”;
Question 3
What happens when you try to compile and run the following code?
1. public class EqualsTest {
2. public static void main(String args[]) {
3. Long LA = new Long ( 7 );
4. Long LB = new Long ( 7 );
5. if (LA == LB)
6. System.out.println(“Equal”);
7. else System.out.println(“Not Equal”);
8. }
9. }
a. The program compiles but throws a runtime exception in line 5.
b. The program compiles and prints “Equal”.
c. The program compiles and prints “Not Equal”.
Question 4
What would happen if you tried to compile and run the following code?
1. public class EqualsTest {
2. public static void main(String args[]) {
3. Long L = new Long ( 7 );
4. if (L.equals( 7L ))
System.out.println(“Equal”);
5. else System.out.println(“Not Equal”);
6. }
7. }
a. The program would compile and print “Equal”.
b. The program would compile and print “Not Equal”.
c. The compiler would object to line 4.
d. A runtime cast error would occur at line 4.
Question 5
What would happen if you tried to compile and run the following code?
1. public class EqualsTest {
2. public static void main(String args[]) {
3. Object A = new Long ( 7 );
4. Long L = new Long ( 7 );
5. if (A.equals( L ))
6. System.out.println(“Equal”);
7. else System.out.println(“Not Equal”);
8. }
9. }
a. The program would compile and prints “Equal”.
b. The program would compile and prints “Not Equal”.
c. The compiler would object to line 5.
d. A runtime cast error would occur at line 5.
Question 6
Given the following listing of the Widget class:
1. class Widget extends Thingee {
2. static private int widgetCount = 0;
3. public String wName;
4. int wNumber;
5. static synchronized int addWidget() {
6. widgetCount++;
7. wName = “I am Widget # ” + widgetCount;
8. return widgetCount;
9. }
10. public Widget() {
11. wNumber = addWidget();
12. }
13. }
What happens when you try to compile the class and use multiple Widget objects in a program?
a. The class compiles and each Widget will get a unique wNumber and wName reflecting the order in which the Widgets were created.
b. The compiler objects to line 7.
c. The class compiles, but a runtime error related to the access of the variable wName occurs in the addWidget method.
Question 7
Trying to compile the following source code produces a compiler warning to the effect that the variable tmp may not have been initialized.
1. class Demo {
2. String msg = “Type is ”;
3. public void showType ( int n ) {
4. String tmp;
5. if ( n > 0 ) tmp = “positive”;
6. System.out.println( msg + tmp );
7. }
8. }
Which of the following changes would eliminate this warning? [Check all correct answers]
a. Make line 4 read
4. String tmp = null;
b. Make line 4 read
4. String tmp = “”;
c. Insert a line following line 5
6. else tmp = “not positive”;
d. Remove line 4 and insert a new line after 2 so tmp becomes a member variable instead of a local variable in showType.
3. String tmp;
Question 8
The following method definition is designed to parse and return an integer from an input string that is expected to look like “nnn, ParamName”. In the event of NumberFormatException, the method is to return –1.
1. public int getNum( String S ) {
2. try {
3. String tmp = S.substring( 0, S.indexOf( ‘,’ ));
4. return Integer.parseInt( tmp );
5. } catch ( NumberFormatException e ) {
6. System.out.println( “Problem in ” + tmp );
7. }
8. return –1;
9. }
What happens when you try to compile this code and execute the method with an input string that does not contain a comma separating the number from the text data?
a. A compiler error in line 6 prevents compilation.
b. The method prints the error message to standard output and returns –1.
c. A NumberFormatException is thrown in line 3.
d. A StringIndexOutOfBoundsException is thrown in line 3.
Question 9
Given the following class definition:
1. public class DerivedDemo extends Demo {
2. int M, N, L;
3. public DerivedDemo( int x, int y ) {
4. M = x; N = y;
5. }
6. public DerivedDemo( int x) {
7. super( x );
8. }
9. }
Which of the following constructor signatures must exist in the Demo class for DerivedDemo to compile correctly? [Check all correct answers]
a. public Demo( int a, int b)
b. public Demo( int c)
c. public Demo( )
Question 10
When programming a local inner class inside a method code block, which of the following statements is true?
a. The inner class will have access only to static variables in the enclosing class.
b. The inner class can use any variables declared in the method.
c. The inner class can use only local variables that are declared final.
d. The inner class can use only local variables that are declared static.
Question 11
You have been given the following programming problem with respect to a Java application. An existing class called AB now needs some additional functionality, which it is proposed to add with a nested inner class, ABC. You have been able to establish the following requirements:
1. There will probably be more than one AB instance active in the application, so the solution has to work no matter how many AB instances there are.
2. ABC will need to have access to instance methods and variables as well as static variable.
3. More than one method in AB will have access to a method of ABC.
Which configuration of a nested class is the best bet for this problem?
a. A static class
b. A member inner class
c. An inner class defined in an AB method
d. An anonymous inner class
Question 12
In the following code for a class in which methodA has an inner class, which variables would the statement in line 8 be able to use in place of XX? [Check all correct answers]
1. public class Base {
2. private static final int ID = 3;
3. private String name;
4. public void methodA( final int nn ) {
5. int serialN = 11;
6. class inner {
7. void showResult( ) {
8. System.outprintln( “Rslt = ” + XX );
9. }
10. } // end class inner
11. new inner( ).showResult( );
12. } // end methodA
13. }
a. The int ID in line 2
b. The String in line 3
c. The int nn in line 4
d. The int serialN in line 5
Question 13
What will happen when you try to compile the following code?
1. public void printArray( Object x ) {
2. if ( x instanceof int[ ] ) {
3. int[ ] n = ( int[ ] ) x;
4. for ( int i = 0; i < n.length; i++ ) {
5. System.out.println( “integers = ” +
n[ i ] );}
6. }
7. if ( x instanceof String[ ] ) {
8. System.out.println( “Array of Strings” ;
9. }
10. }
a. It compiles without error.
b. The compiler objects to line 2 comparing an Object with an array.
c. The compiler objects to line 3 casting an Object to an array of int primitives.
d. The compiler objects to line 7 comparing an Object to an array of Objects.
Answer is : System.out.println( “Array of Strings” ;
) excepted
Question 14
Here is the class hierarchy showing the java.awt.event.ActionEvent class family tree:
java.lang.Object
|-- java.util.EventObject
|-- java.awt.AWTEvent
|-- java.awt.event.ActionEvent
Suppose you have the following code to count events and save the most recent event.
1. int evtCt = 0;
2. AWTEvent lastE;
3. public void saveEvent( AWTEvent evt ) {
4. lastE = evt;
5. evtCt++;
6. }
Which of the following calls of saveEvent would run without causing an exception? [Check all correct answers]
a. an AWTEvent object reference
b. an ActionEvent object reference
c. an EventObject object reference
d. null value
Question 15
Suppose you have two classes defined as follows:
class ApBase extends Object implements Runnable
class ApDerived extends ApBase implements Observer
Given two variables created as follows:
ApBase aBase = new ApBase( );
ApDerived aDer = new ApDerived( );
Which of the following Java statements will compile and execute without error? [Check all correct answers]
a. Runnable rn = aDer;
b. Runnable rn2 = (Runnable) aBase;
c. Observer ob = aBase;
d. Observer ob2 = (Observer) aBase;
Question 16
The following method is designed to convert an input string to a floating-point number while detecting a bad format.
1. public boolean strCvt( String s ) {
2. try {
3. factor = Float.valueOf( s ).floatValue( );
4. return true;
5. } catch ( NumberFormatException e ) {
6. System.out.println( “Bad number ” + s );
7. factor = Float.NaN;
8. } finally { System.out.println( “Finally” );
9. }
10. return false;
11. }
Which of the following descriptions of the results of various inputs to the method are correct? [Check all correct answers]
a. Input = “0.234” – Result: factor = 0.234, “Finally” is printed, true is returned.
b. Input = “0.234” – Result: factor = 0.234, “Finally” is printed, false is returned.
c. Input = null – Result: factor = NaN, “Finally” is printed, false is returned.
d. Input = null – Result: factor unchanged, “Finally” is printed, NullPointerException is thrown.
Question 17
Here is the class hierarchy of exceptions related to array index and string index errors:
Exception
+-- RuntimeException
+-- IndexOuOfBoundsException
+-- ArrayIndexOuOfBoundsException
+-- StringIndexOuOfBoundsException
Suppose you had a method X that could throw both array index and string index exceptions. Assuming that X does not have any try-catch statements, which of the following statements are correct? [Check all correct answers]
a. The declaration for X must include “throws ArrayIndexOuOfBoundsException, StringIndexOuOfBoundsException”.
b. If a method calling X catches IndexOuOfBoundsException, both array and string index exceptions will be caught.
c. If the declaration for X includes “throws IndexOuOfBoundsException”, any calling method must use a try catch block.
d. The declaration for X does not have to mention exceptions.
Question 18
You are writing a set of classes related to cooking and have created your own exception hierarchy derived from java.lang.Exception as follows:
Exception
+-- BadTasteException
+-- BitterException
+-- SourException
Your custom exceptions have constructors taking a String parameter. You have a method declared as follows:
int rateFlavor( Ingredient[ ] list ) throws BadTasteException
Which of the following shows a correct complete statement to throw one of your custom exceptions?
a. new SourException( “Ewww!” );
b. throws new SourException( “Ewww!” );
c. throw new SourException( “Ewww!” );
d. throw SourException( “Ewww!” );
Question 19
The GenericFruit class declares the following method:
public void setCalorieContent( float f )
You are writing a class Apple to extend GenericFruit and want to add methods that overload the method in GenericFruit. Which of the following would constitute legal declarations of overloading methods? [Check all correct answers]
a. protected float setCalorieContent( String s )
b. protected void setCalorieContent( float x )
c. public void setCalorieContent( double d )
d. public void setCalorieContent( String s ) throws NumberFormatException
Question 20
The GenericFruit class declares the following method to return a float number of calories in the average serving size:
public float aveCalories( )
Your Apple class, which extends GenericFruit, overrides this method. In a DietSelection class that extends Object, you want to use the GenericFruit method on an Apple object. Select the correct way to finish the statement in the following code fragment so the GenericFruit version of aveCalories is called using the gf reference, or select option d.
1. GenericFruit gf = new Apple( );
2. float cal = // finish this statement using gf
a. gf.aveCalories( );
b. ( ( GenericFruit ) gf ).aveCalories( );
c. gf.super.aveCalories( );
d. There is no way to call the GenericFruit method.
Question 21
The GenericFruit class declares the following method to return a float calculated from a serving size:
protected float calories( float serving )
In writing the Apple class that extends GenericFruit, you propose to declare an overriding method with the same parameter list and return type. Which access modifiers could you use with this overriding method? [Check all correct answers]
a. private
b. protected
c. public
d. “package”; that is, a blank access modifier
Question 22
Which of the following statements about the java.util.Vector and java.util.Hashtable classes are correct? [Check all correct answers]
a. A Vector can hold object references or primitive values.
b. A Vector maintains object references in the order they were added.
c. A Hashtable requires String objects as keys.
d. A Hashtable maintains object references in the order they were added.
e. Both Vector and Hashtable use synchronized methods to avoid problems due to more than one Thread trying to access the same collection.
Question 23
In the following class definitions, which are in separate files, note that the Widget and BigWidget classes are in different packages:
1. package conglomo;
2. public class Widget extends Object {
3. private int myWidth;
4. XXXXXX void setWidth( int n ) {
5. myWidth = n;
6. }
7. }
// the following is in a separate file
8. import conglomo.Widget;
9. public class BigWidget extends Widget {
10. BigWidget( ) {
11. setWidth( 204 );
12. }
13. }
Which of the following modifiers, used in line 4 instead of XXXXXX, would allow the BigWidget class to access the Widget.setWidth method (as in line 11)? [Check all correct answers]
a. private
b. protected
c. blank – that is, the method declaration would read void setWidth( int n )
d. public
Question 24
What happens on trying to compile and run the following code?
1. public class EqualsTest {
2. public static void main( String args[ ] ) {
3. float pear = 0.0F;
4. for(int i = 0; i<10; i++) pear = pear + 0.1F;
5. if (pear == 1.0F)
System.out.println( "Equal" );
6. if (pear != 1.0F)
System.out.println( "Not Equal" );
7. }
8. }
a. The program compiles and prints “Not Equal”.
b. The program compiles and prints “Equal”.
c. The compiler objects to line 3.
d. The compiler objects to using == with primitives in line 5.
Question 25
Given the following method in an application
1. public String setFileType( String fname ) {
2. int p = fname.indexOf( ‘.’ );
3. if( p > 0 ) fname = fname.substring( 0, p );
4. fname += “.txt”;
5. return fname;
6. }
and given that another part of the class has the following code
7. String TheFile = “Program.java”;
8. File F = new File( setFileType( TheFile ) );
9. System.out.println( “Created ” + TheFile );
what will be printed by the statement in line 9?
a. Created Program.java
b. Created Program.txt
c. Created Program.java.txt
Question 26
What happens when this method is called with an input of “Java rules”?
1. public String addOK( String S) {
2. S += “ OK!”;
3. return S;
4. }
a. The method will return “ OK!”;
b. A runtime exception will be thrown.
c. The method will return “Java rules OK!”.
d. The method will return “Java rules”.
Question 27
Which of the following code fragments are legal Java code? [Check all correct answers]
a. String A = “abcdefg”;
A -= “cde”;
b. String A = “abcdefg”;
A += “cde”;
c. Integer J = new Integer( 27 );
J -= 7;
d. Integer J = new Integer( 27 );
J--;
Question 28
Which statements regarding the following method definition are true?
boolean e() {
try {
assert false;
} catch (AssertionError ae) {
return true;
}
return false; // (1)
}
The code will fail to compile since catching AssertionError is illegal
The code will fail to compile since the return statement at (1) is unreachable
The method will return true under all circumstances
The method will return false under all circumstances
The method will return true if and only if assertions are enabled at runtime
Question 29
Which of the following statements are true?
The instanceof operator can be used to determine if a reference is an instance of a class, but not an interface.
transient and volatile are Java modifiers.
Constructors are not inherited.
A static method may not be overriden to be non-static.
The size of a string can be retrieved using the length property.
Question 30
What will be written to the standard output when the following program is run?
class Base {
int i;
Base() { add(1); }
void add(int v) { i += v; }
void print() { System.out.println(i); }
}
class Extension extends Base {
Extension() { add(2); }
void add(int v) { i += v*2; }
}
public class Qd073 {
public static void main(String[] args) {
bogo(new Extension());
}
static void bogo(Base b) {
b.add(8);
b.print();
}
}
9
18
20
21
22
Java Design Patterns
Java Design Patterns
1. Introduction
A design pattern is a general repeatable solution to a commonly occurring problem in a software design.
A design pattern is an abstraction of a solution at a very high level. Many designers and architects have defined the term design patterns in various ways.
Design patterns address the recurring design problems that arise in particular design situations and propose solutions to them. Design patterns are thus successful solutions to known problems. There are various ways to implement design patterns. There implementation details are called Strategies.
A design pattern prescribes a proven solution from experienced hands for a recurring design problem. Apart from describing the problem and prescribing the solution, the pattern will also explain the implementation issues involved and consequences, if any, of using the pattern. These solutions are generic in nature. They are described in the well-defined "Pattern Templates"; the most common one in use is the template defined by the "Gang of Four." The pattern templates usually have a name that offers a good idea as to what that pattern is all about, followed by where the pattern is applicable, the motivation, implementation issues, and other descriptions.
Use of such patterns makes the design of an application transparent. These patterns have been used successfully by developers in their respective work and hence the pros and cons of their use as well as implementation issues are known beforehand. All design patterns are reusable and can be adapted to a particular context; this gives developers flexibility. The use of design patterns related to J2EE applications offer the added advantage of providing solutions for J2EE platform technologies
2. Applications of Design Patterns
They have been proven. Patterns reflect the experience, knowledge and insights of developers who have successfully used these patterns in their own work.
They are reusable. Patterns provide a readymade solution that can be adapted to different problems as necessary.
They are expressive. Patterns provide a common vocabulary of solutions that can express very large solutions succinctly.
It is important to remember that patterns do not guarantee success. A pattern description indicates when the pattern may be applicable, but only experience can provide understanding of when a particular pattern will improve a design.
3. Origin of Design Patterns
The civil engineering patterns
In the 1960s and ’70s, Christopher Alexander, professor of architecture and director of the Center for Environmental Structure, along with his colleagues, wrote a number of books describing and documenting the principles of civil engineering from a layperson’s point of view. Of them, one of the most widely known books is A Pattern Language: Towns, Buildings, and Constructions. It provides practical guidance on how to build houses, construct buildings and parking lots, design a good neighborhood, and so forth. The book examines how these simple designs integrate with each other to create well-planned towns and cities. As its title suggests, the book describes 253 patterns that are split into three broad categories: towns, buildings, and construction.
4. Design Patterns classification
The Gang of Four Patterns
Software Designers extended the idea of design patterns to software development. Since features provided by the object-oriented languages, such as inheritance, abstraction, and encapsulation, allowed them to easily relate programming language entities to real-world entities, designers started applying those features to create common and reusable solutions to recurring problems that exhibited similar patterns.
Around 1994, the now famous Gang of Four(GoF)—Erich Gamma, Richard Helm,Ralph Johnson, and John Vlissides-documented 23 such software design patterns.
They classified the patterns at the very top level into three types of categories based on their purpose ---creational, structural, and behavioral.
Creational----Creational patterns deal with the ways to create instances of objects. The objective of these patterns is to abstract the instantiation process and hide the details of how objects are created or initialized.
Structural------Structural patterns describe how classes and objects can be combined to form larger structures and provide new functionality. These aggregated objects can be either simple objects or composite objects themselves.
Behavioral----Behavioral patterns help us define the communication and interaction between the objects of a system. The purpose of these patterns is to
reduce coupling between objects.
Though the GoF patterns served well in designing and developing object-oriented systems in both distributed and non distributed environments, they were not created with the distributed nature of large-scale enterprise systems in mind. As the demands for more distributed enterprise applications grew, the architects felt the need to document the solutions to recurring problems as they experienced the same problem occurring over and over again. They started extending and refining the patterns over a larger scale and with a broader scope.
The J2EE patterns
With the advent of the J2EE, a whole new catalog of deign patterns cropped up. Since J2EE is an architecture in itself that comprises other architectures, including servlets, Java Server Pages, Enterprise Java Beans, and so forth, it deserves its own set of patterns specifically tailored to the various types of enterprise applications that the architecture addresses.
There are 5 tiers in J2EE architecture. They are
a. Client
b. Presentation
c. Business
d. Integration
e. Resource
A Tier is a logical partition of the components involved in the system. Each tier is a loosely coupled with the adjacent tier. It is easier to understand the role of design patterns once we fully grasp the different tiers involved in a J2EE application.
Client---The tier comprises all the types of components that are clients of the enterprise application. Examples of client components are a Web browser, a hand held device, or another application that accesses the services of the enterprise application remotely.
Presentation---This tier interfaces with the client tier and encapsulates the presentation logic. It accepts the requests, handles authentication and authorization, manages client sessions, delegates the business processing to the business tier, and presents the client with the defined response. The components that make up this tier are filters, servlets, Java Beans, JSP pages, and other utility classes.
Business--- This tier is the heart of the enterprise application and implements the core business services. It is normally composed of the Enterprise Java Beans components that handle all the business processing rules.
Integration--- The job of this tier is to seamlessly integrate different types of external resources in the resource tier with the components of the business tier. The components that make up the integration tier use various mechanisms like JDBC,J2EE connector technology, or proprietary middleware to access the resource tier.
Resource--- This tier comprises the external resources that provide actual data to the application. The resources can either be data sources such as relational databases and file-based databases or such as applications running on mainframes. Other legacy systems, modern business-to-business(B2B)systems, and third party services like credit card authorization services.
Each of the 15 J2EE design patterns fall in one of the five tiers.
Presentation Tier
• Decorator Filter/Intercepting Filter
• Front Controller/Front Component
• View Helper
• Composite View
• Service to Worker
• Dispatcher View
Business Tier
• Business Delegate
• Transfer Object/Replicate Object
• Session Façade/Session Entity Façade/ Distributed Façade
• Aggregate Entity
• Transfer Object Assembler
• View List Handler/Page-by-Page Iterator /Paged List
• Service Locator
Integration Layer
• Data Access Object
• Service Activator
MVC is most commonly heard name in J2EE domain is in fact not a J2EE design pattern instead it is an architecture.
1)Decorator Filter/Intercepting Filter
Context—
• Client request may have many processing needs, and the system must be able to meet them.
• The System receives requests using multiple protocols, such as HTTP,FTP, or SMTP.
• The System must authorize or authenticate some requests, while handling others directly.
• The System needs to add or remove information from requests are responses before further processing.
Example--
If you have to build an enterprise system that doubles as a web portal and corporate intranet, you need to ensure that different client requests are handled appropriately. Not only must the system block requests for secure resources, it must also check for trusted IP addresses. Further, it must ensure that responses and requested resources are compressed/decompressed and encrypted/decrypted as needed.
Solution—
The Solution is to separate request/response processing from the rest of the system by creating filters. These objects, more fully provide a standardized, replaceable means of altering requests and responses as needed.
2)Front Controller/Front Component
Context—
• Managing an application for an individual user requires a number of considerations
• Controlling the application’s view and navigation
• Performing security processing to determine which resources and services are available for the user.
• Activating system services according to user selection
• Locating and accessing available resources according to user selection
Example—
In a Web application that accepts credit card information, several steps must be completed.
• Browse the catalog
• Add items to the shopping cart
• Confirm the checkout
• Get the name and shipping address of the receiver
• Get the name and billing address and the credit card information of the payer.
The different views associated with the store are decentralized. This means that they each control their navigation function, as well as perform the tasks needed to dispatch the user’s request.
Solution—
we need a single object to manage view control, resource/service accessing, error handling and initial request processing. This object acts as a front door to the client and is called as front controller or Front Component. Among the various strategies suggested by J2EE, the two simplest ones are using a servlet or JSP as front objects. All requests will be sent to the Front Controller and each request will have an action as a parameter.
3) Service Locator
Context-
Many systems depend on distributed processing and communication. In these cases, a number of concerns must be kept in mind:
• The system needs to locate and access resources and services across networks.
• If the services or resources are unavailable, the system must create local
implementations.
• New requests to a directory service require more time and resources than
cached repetitions of previous requests.
Example—
A large company contains a number of worldwide branches and needs to maintain
communication throughout. Many different applications require access to similar
external resources, such as personnel databases and inventory listings. In this case, the system uses Java Naming and Directory Interface (JNDI) to help components find one another. But as each object accesses JNDI separately, its responsiveness slows.
Solution –
The solution is to encapsulate the process of external communication into a Service Locator. With this method, the Locator object manages all of the complexity related to locating and interfacing resources across the network. Further, to reduce the amount of time associated with making requests, they can provide request caching. Finally, if external resources have vendor-specific interfaces, this object will manage the communication complexity and make accessing the resource transparent to the user.
4) Business Delegate
Context—
In an enterprise-scaled distributed application, typically the following situation arises:
• There are separate components to interact with the end users and to handle
business logic.
• These separate components reside in different subsystems, separated by a
network.
• The components that handle the business logic act as server components
because they provide business services to the clients by exposing the business
service API to the clients.
• The client components that use this API often reside in a remote system
separated by a network.
• There is more than one client using the API.
• There is more than one server component providing similar services, but with
minor differences in the API.
Example –
Let’s look at a real-world example. A company is building a web-based application
with JSP pages and servlets that need to access a set of business services. The management has decided not to develop the business services in-house, since they are readily available as off-the-shelf software from various vendors. In addition, the budget for the project is currently tight, so management has decided that they will purchase one of the more economical off-the-shelf solutions initially, and then when the money becomes available in a year, they will replace it with a more elaborate and expensive software solution.
Solution
Create a Business Delegate to handle all of the code that accesses the business services in the selected vendor software. When the vendor changes, the only changes that need to be made to the company’s application software are changes to the Business Delegate, to access the business services in the new vendor software. The JSP pages and servlets will not have to be modified.
The responsibilities of the components participating in this pattern are
• Client components—The client components, which are JSP pages and servlets in
the presentation tier, delegate the work of locating the business service providers
and the work of invoking the business service API methods to the Business Delegate objects.
• Business Delegate—The Business Delegate acts as a representative of the client
components. It knows how to look up and access the business services. It invokes the appropriate business services methods in the required order. If the API of the business service component changes, only the Business Delegate needs to be modified, without affecting the client components.
• Business service—A business service component implements the actual business
logic. Some examples of business service components are a stateless session EJB,
an entity EJB, a CORBA object, or an RPC server.
5) Transfer Object
Context
In distributed applications, the following situation typically arises:
• The client-side and the server-side components reside at remote locations and
communicate over the network.
• The server handles the database.
• The server provides getter methods to the clients so that the clients can call
those getter methods one by one to retrieve database values.
• The server provides setter methods to the clients so that the clients can call
those setter methods one by one to update database values.
Example
In the J2EE architecture, the business tier accesses the database directly or via the resource tier, and wraps the data access mechanism inside a set of entity beans and session beans. These entity and session beans expose the data via remote interfaces. The servlets and JSP pages in the presentation tier that need to access business data can do so by calling methods on the remote interfaces implemented by the beans.
As a specific example, suppose we maintain the address information in the database of the registered users of our enterprise application. In this case, the address information, which is a summation of four other pieces of data—street, city, state, and, zip—is a business entity. The access to this information is encapsulated by the application’s business tier with the help of a session bean called AddressSessionBean. AddressSessionBean exposes methods for the remote clients, such as getState (), setState(), getCity (), and setCity(). The servlets and the JSP pages then have to call each of the methods one by one on the remote server, as shown in figure below.
Solution
Create an object to encapsulate all of the attribute values that are required by the client application. This object is called the Transfer Object. When the client requests the data from the server, the server-side component gathers the data values and constructs the Transfer Object by setting its data values. This object is then sent to the client by value (not by reference), which means that the whole object is serialized and each of its bits is transferred over the network.
The client on the other side reconstructs this object locally with all the values intact. It can then query this local instance for all the attribute values. Because the Transfer Object is local on the client, all of the calls to this object are local and do not incur any network overhead. The Transfer Object on the client serves as a proxy for the properties of the remote object. This scenario is shown in figure below.
Now, instead of making multiple remote calls on the business object, Address-
Bean, to retrieve all the attributes, the client calls a single method, getAddress(),
which returns all the attributes structured in an AddressVO object.
6) Composite View
Context
In an enterprise-scaled distributed application, typically the following situation arises:
In distributed applications, the following situation typically arises:
• The web pages present data from various data sources, using multiple sub views that comprise a single display page.
• The server handles the database.
The Server may need to be restarted before clients see the modifications are updates to the template components.
Example
In real world application web pages present content from numerous data sources, using multiple sub views that comprise a single display page. The web pages are built by embedding formatting code directly with each atomic view. Atomic portion of the view content changes frequently , modification to the layout of multiple views is difficult and error prone when sub views are directly embedded and duplicated in multiple views. Embedding frequently changing portions of template text directly into views also potentially affects the availability and administration of the system.
Solution
The solution to this is to use composite views that are composed of multiple atomic sub views. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content.
This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design. It is appropriate to use a composite view to generate pages containing display components that may be combined in a variety of ways. The layout of the page is managed and modified independent of the subview content.
The responsibilities of the components participating in these patterns are :
Composite View:--
A composite view is a view that is an aggregate of multiple subviews.
View Manager:--
The View Manager manages the inclusion of portions of template fragments into the composite view. The View Manager may be part of a standard JSP page runtime engine, in the form of the standard Java Server Pages (JSP page) pages include tag (), or it may be encapsulated in a JavaBeans helper (JSP page 1.0+) or custom tag helper (JSP page 1.1+) to provide more robust functionality. A benefit of using a mechanism other than the standard include tag is that conditional inclusion is easily done. For example,
certain template fragments may be included only if the user fulfills a particular role or certain system conditions are satisfied. Furthermore, using a helper component as a View Manager allows for more sophisticated control of the page structure as a whole, which is useful for creating reusable page layouts.
IncludedView--
An included view is a subview that is one atomic piece of a larger whole view. This included view could also potentially be a composite, itself including multiple subviews.
7) Data Access Object
Context
Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
If the client needs to display or update a set of attributes that live on the server, these attributes could live in an entity bean or be accessible through a session bean. The client could get or update the data is by loading many parameters into a method call, when updating data on the server, or by making multiple fine-grained calls to the server to retrieve data. Every call between the client and server is a remote method call with substantial network overhead. If the client application calls the individual getter and setter methods that require or update single attribute values, it will require as many remote calls as there are attributes. The individual calls generate a lot of network traffic and affects severely the system performance.
To deal with suck kind of scenario we need to go for the DAO pattern.
Example
Suppose if the user want to send data a number of times through the program like entering user personal information or accessing just like online transactions services etc, we need to go for this approach.
Solution
The solution to this problem is to use a plain java classes called Value Objects or Transfer Objects which encapsulate the bulk business data. A single method call is used to send and retrieve the Transfer Object / Value Objects. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client.
8) Session Façade/Session Entity Façade/Distributed Facade
Context
Enterprise beans encapsulate business logic and business data and expose their interfaces, and thus the complexity of the distributed services, to the client tier.
In a multitiered Java 2 Platform, Enterprise Edition (J2EE) application environment, the following problems arise:
• Tight coupling, which leads to direct dependence between clients and business objects;
• Too many method invocations between client and server, leading to network performance problems;
• Lack of a uniform client access strategy, exposing business objects to misuse.
Example
An example demonstrating the use of Session Facade design pattern in a typical HR application.
Employees and Departments are used to store and retrieve employee and department information from the database. addition, the application allows the user to add a new department and assign existing employees to the newly added department. As this involves accessing two different entities, it should take place in one transaction. In this application only the admin user is allowed to add a new department.
Solution
Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.
The Session Facade abstracts the underlying business object interactions and provides a service layer that exposes only the required interfaces. Thus, it hides from the client's view the complex interactions between the participants. The Session Facade manages the interactions between the business data and business service objects that participate in the workflow, and it encapsulates the business logic associated with the requirements. Thus, the session bean (representing the Session Facade) manages the relationships between business objects. The session bean also manages the life cycle of these participants by creating, locating (looking up), modifying, and deleting them as required by the workflow. In a complex application, the Session Facade may delegate this lifestyle management to a separate object. For example, to manage the lifestyle of participant session and entity beans, the Session Facade may delegate that work to a Service Locator object
9) Service Activator
Context
An application has a service that it would like to make available to other applications.
Example
A Typical web application which requires the service of an authentication mechanism for a user is put in this service activator, and is invoked each time a user is login.
Solution
A Service Activator Service Activator can be one-way (request only) or two-way (Request-Reply). The service can be as simple as a method call—synchronous and non-remote—perhaps part of a Service Layer The activator can be hard-coded to always invoke the same service, or can use reflection to invoke the service indicated by the message. The activator handles all of the messaging details and invokes the service like any other client, such that the service doesn’t even know its being invoked through messaging.
The architecture of the Service Activator can be seen from the figure above.
10) Dispatcher View
Context
System controls flow of execution and access to presentation processing, which is responsible for generating dynamic content.
The Dispatcher View pattern, like the Service to Worker pattern, describes a common combination of other patterns from the catalog. Both of these macro patterns describe the combination of a controller and dispatcher with views and helpers. While describing this common structure, they emphasize related but different usage patterns.
Example
Authentication and authorization checks are completed per request. Scriptlet code within views should be minimized. Business logic should be encapsulated in components other than the view.
Control flow is relatively simple and is typically based on values encapsulated with the request.
View management logic is limited in complexity.
Solution
Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers do not delegate content retrieval to helpers, because these activities are deferred to the time of view processing. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller, a view, or a separate component.
Dispatcher View describes the combination of the Front Controller and View Helper patterns with a dispatcher component. While this pattern and the Service to Worker pattern describe a similar structure, the two patterns suggest a different division of labor among the components. The controller and the dispatcher typically have limited responsibilities, as compared to the Service to Worker pattern, since the upfront processing and view management logic are basic. Furthermore, if centralized control of the underlying resources is considered unnecessary, then the controller is removed and the dispatcher may be moved into a view.
Since the Service to Worker and Dispatcher View patterns represent a common combination of other patterns from the catalog, each warrants its own name to promote efficient communication among developers. Unlike the Service to Worker pattern, the Dispatcher View pattern suggests deferring content retrieval to the time of view processing.
In the Dispatcher View pattern, the dispatcher typically plays a limited to moderate role in view management. In the Service to Worker pattern, the dispatcher typically plays a moderate to large role in view management.
A limited role for the dispatcher occurs when no outside resources are utilized in order to choose the view. The information encapsulated in the request is sufficient to determine the view to dispatch the request.
For example:
http://some.server.com/servlet/Controller?next=login.jsp
The sole responsibility of the dispatcher component in this case is to dispatch to the view login.jsp.
An example of the dispatcher playing a moderate role is the case where the client submits a request directly to a controller with a query parameter that describes an action to be completed:
http://some.server.com/servlet/Controller?action=login
The responsibility of the dispatcher component here is to translate the logical name login into the resource name of an appropriate view, such as login.jsp, and dispatch to that view. To accomplish this translation, the dispatcher may access resources such as an XML configuration file that specifies the appropriate view to display.
On the other hand, in the Service to Worker pattern, the dispatcher might be more sophisticated. The dispatcher may invoke a business service to determine the appropriate view to display.
The shared structure of these two patterns, as mentioned above, consists of a controller working with a dispatcher, views, and helpers.
The figure above shows the class diagram that represents the Dispatcher View pattern.
11) Service to Worker
Context
The system controls flow of execution and access to business data, from which it creates presentation content.
A service to Worker pattern like the Dispatcher View pattern, describes a common combination of other patterns from the catalog. Both of these macro patterns describe the combination of controller and dispatcher with views and helpers. While describing this common structure, they emphasize related but different usage patterns.
Example
Authentication and authorization checks are completed per request. Scriptlet code within views should be minimized. Business logic should be encapsulated in components other than the view. Control flow is relatively complex and based on values from dynamic content. View management logic is relatively sophisticated, with multiple views potentially mapping to the same request.
Solution
Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers delegate content retrieval to helpers, which manage the population of the intermediate model for the view. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller or a separate component.
Service to Worker describes the combination of the Front Controller and View Helper patterns with a dispatcher component.
While this pattern and the Dispatcher View pattern describe a similar structure, the two patterns suggest a different division of labor among the components. In Service to Worker, the controller and the dispatcher have more responsibilities.
Since the Service to Worker and Dispatcher View patterns represent a common combination of other patterns from the catalog, each warrants its own name to promote efficient communication among developers. Unlike the Service to Worker pattern, the Dispatcher View pattern suggests deferring content retrieval to the time of view processing.
In the Dispatcher View pattern, the dispatcher typically plays a limited to moderate role in view management. In the Service to Worker pattern, the dispatcher typically plays a moderate to large role in view management.
A limited role for the dispatcher occurs when no outside resources are utilized in order to choose the view. The information encapsulated in the request is sufficient to determine the view to dispatch the request. For example,
http://some.server.com/servlet/Controller?next=login.jsp
The sole responsibility of the dispatcher component in this case is to dispatch to the view login.jsp.
An example of the dispatcher playing a moderate role is the case where the client submits a request directly to a controller with a query parameter that describes an action to be completed:
http://some.server.com/servlet/Controller?action=login
The responsibility of the dispatcher component here is to translate the logical name login into the resource name of an appropriate view, such as login.jsp, and dispatch to that view. To accomplish this translation, the dispatcher may access resources such as an XML configuration file that specifies the appropriate view to display.
On the other hand, in the Service to Worker pattern, the dispatcher might be more sophisticated. The dispatcher may invoke a business service to determine the appropriate view to display.
The shared structure of Service to Worker and Dispatcher View consists of a controller working with a dispatcher, views, and helpers.
The class diagram given above represents the Service to Worker pattern.
12)ViewHelper
Context
The system creates presentation content, which requires processing of dynamic business data.
Example
Business data assimilation requirements are nontrivial. Embedding business logic in the view promotes a copy-and-paste type of reuse. This causes maintenance problems and bugs because a piece of logic is reused in the same or different view by simply duplicating it in the new location. It is desirable to promote a clean separation of labor by having different individuals fulfill the roles of software developer and Web production team member.
One view is commonly used to respond to a particular business request.
Solution
A view contains formatting code, delegating its processing responsibilities to its helper classes, implemented as JavaBeans or custom tags. Helpers also store the view's intermediate data model and serve as business data adapters.
There are multiple strategies for implementing the view component. The JSP View Strategy suggests using a JSP as the view component. This is the preferred strategy, and it is the one most commonly used. The other principal strategy is the Servlet View Strategy, which utilizes a servlet as the view (see the section "Strategies" for more information).
Encapsulating business logic in a helper instead of a view makes our application more modular and facilitates component reuse. Multiple clients, such as controllers and views, may leverage the same helper to retrieve and adapt similar model state for presentation in multiple ways. The only way to reuse logic embedded in a view is by copying and pasting it elsewhere. Furthermore, copy-and-paste duplication makes a system harder to maintain, since the same bug potentially needs to be corrected in multiple places.
A signal that one may need to apply this pattern to existing code is when scriptlet code dominates the JSP view. The overriding goal when applying this pattern, then, is the partitioning of business logic outside of the view. While some logic is best encapsulated within helper objects, other logic is better placed in a centralized component that sits in front of the views and the helpers-this might include logic that is common across multiple requests, such as authentication checks or logging services.
If a separate controller is not employed in the architecture, or is not used to handle all requests, then the view component becomes the initial contact point for handling some requests. For certain requests, particularly those involving minimal processing, this scenario works fine. Typically, this situation occurs for pages that are based on static information, such as the first of a set of pages that will be served to a user to gather some information Additionally, this scenario occurs in some cases when a mechanism is employed to create composite pages .
The View Helper pattern focuses on recommending ways to partition your application responsibilities. For related discussions about issues dealing with directing client requests directly to a view.
Figure above is the class diagram representing the View Helper pattern.
13) View List Handler/Page-by-Page Iterator /Paged List
Context
This design pattern describes how to break a huge list of values into smaller pages and display the results one page at a time.
Example
In an application each user account is associated with many trade details and port folio details. Fetching all the data at once can be inefficient. It can take a long time, increase network traffic, and the user may only want to see a record or two.
Solution
Use a Page-by-Page Iterator to have a client object traverse a large list, one sublist or page of value objects at a time; each page can be as big or as small as the client desires.
Using this pattern makes the Less server-side data is transferred. More server side requests are made, The Iterator is not a robust Iterator.
The Iterator can be implemented as a Stateful Session Bean- so that it can keep the state of the Iterator for each client. It can cache the retrieved the pages which makes subsequent reads perform better.
We can use a Stateless Session Bean- as it has no state for the client; they have to specify what is wanted in each call. Cached pages are shared between clients.
Always use Value Objects for returned pages, do not return a collection of Entity Beans.
Use server side filtering to avoid unnecessary data transmitted to the client. Consider network load vs. server-side requests when determine the size of the pages.
14) Transfer Object Assembler
Context
In J2EE application, the server-side business components are implemented using session beans, entity beans, DAOs, and so forth. Application clients frequently need to access data that is composed from multiple objects.
Example
Separation of business logic is required between the client and the server-side components.
Because the model consists of distributed components, access to each component is associated with a network overhead. It is desirable to minimize the number of remote method calls over the network. The client typically needs only to obtain the model to present it to the user. If the client must interact with multiple components to construct the model on the fly, the chattiness between the client and the application increases. Such chattiness may reduce the network performance. Even if the client wants to perform an update, it usually updates only certain parts of the model and not the entire model. Clients do not need to be aware of the intricacies and dependencies in the model implementation. It is desirable to have loose coupling between the clients and the business components that implement the application model. Clients do not otherwise need to have the additional business logic required to construct the model from various business components.
Solution
Use a Transfer Object Assembler to build the required model or sub model. The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.
The Transfer Object Assembler constructs a composite Transfer Object that represents data from different business components. The Transfer Object caries the data for the model to the client in a single method call. Since the model data can be complex, it is recommended that this Transfer Object be immutable. That is, the client obtains such Transfer Objects with the sole purpose of using them for presentation and processing in a read-only manner. Clients are not allowed to make changes to the Transfer Objects.
When the client needs the model data, and if the model is represented by a single coarse-grained component (such as a Composite Entity), then the process of obtaining the model data is simple. The client simply requests the coarse-grained component for its composite Transfer Object. However, most real-world applications have a model composed of a combination of many coarse-grained and fine-grained components. In this case, the client must interact with numerous such business components to obtain all the data necessary to represent the model. The immediate drawbacks of this approach can be seen in that the clients become tightly coupled to the model implementation (model elements) and that the clients tend to make numerous remote method invocations to obtain the data from each individual component.
In some cases, a single coarse-grained component provides the model or parts of the model as a single Transfer Object (simple or composite). However, when multiple components represent the model, a single Transfer Object (simple or composite) may not represent the entire model. To represent the model, it is necessary to obtain Transfer Objects from various components and assemble them into a new composite Transfer Object. The server, not the client, should perform such "on-the-fly" construction of the model.
Figure given above shows the class diagram representing the relationships for the Transfer Object Assembler pattern.
15)Aggregate Entity
Context
Entity beans are not intended to represent every persistent object in the object model. Entity beans are better suited for coarse-grained persistent business objects.
Example
Entity beans are best implemented as coarse-grained objects due to the high overhead associated with each entity bean. Each entity bean is associated with an EJB home, remote object, bean implementation, and primary key, and each is managed by the container services.
Applications that directly map relational database schema to entity beans (where each row in a table is represented by an entity bean instance) tend to have a large number of fine-grained entity beans. It is desirable to keep the entity beans coarse-grained and reduce the number of entity beans in the application.
Solution
Use Aggregate Entity bean to model, represent, and manage a set of inter-related persistent objects rather than representing them as individual fine-grained entity beans. An Aggregate Entity bean represents a tree of objects.
To understand aggregation in the context of this pattern, one must first understand persistent objects and their relationships in an application. A persistent object is an object that is stored in some type of data store. Multiple clients usually share persistent objects.
Persistent objects can be classified into two types: coarse-grained objects and dependent objects.
A coarse-grained object is self-sufficient. It has its own life cycle and manages its relationships to other objects. Each coarse-grained object may reference or contain one or more other objects. The coarse-grained object usually manages the life cycles of these objects. Hence, these objects are called dependent objects. A dependent object can be a simple self-contained object or may in turn contain other dependent objects.
The life cycle of a dependent object is tightly coupled to the life cycle of the coarse-grained object. A client may only indirectly access a dependent object through the coarse-grained object. That is, dependent objects are not directly exposed to clients because their parent (coarse-grained) object manages them. Dependent objects cannot exist by themselves. Instead, they always need to have their coarse-grained (or parent) object to justify their existence.
Typically, you can view the relationship between a coarse-grained object and its dependent objects as a tree. The coarse-grained object is the root of the tree (the root node). Each dependent object can be a standalone dependent object (a leaf node) that is a child of the coarse-grained object. Or, the dependent object can have parent-child relationships with other dependent objects, in which case it is considered a branch node.
An Aggregate Entity bean can represent a coarse-grained object and all its related dependent objects. Aggregation combines inter-related persistent objects into a single entity bean, thus drastically reducing the number of entity beans required by the application. This leads to a highly coarse-grained entity bean that can better leverage the benefits of entity beans than fine-grained entity beans.
Without the Aggregate Entity approach, there is a tendency to view each coarse-grained and dependent object as a separate entity bean, leading to a large number of entity beans.
While there are many strategies in implementing the Aggregate Entity pattern, the first one we discuss is represented in the following class diagram. Here the Aggregate Entity contains the coarse-grained object, and the coarse-grained object contains dependent objects.
While there are many strategies in implementing the Aggregate Entity pattern, the first one we discuss is represented in the following class diagram. Here the Aggregate Entity contains the coarse-grained object, and the coarse-grained object contains dependent objects.
The Diagram above shows the Class diagram for the Aggregate Entity Design Pattern.
.
5. Anti Patterns
Anti patterns also called pitfalls, are classes of commonly reinvented bad solutions to problems. Anti-patterns are natural counterparts or follow-on to the study of design patterns. Programmers should try to avoid anti-patterns whenever possible, which requires diagnosing them as early as possible in the software life cycle.
6. Benefits and Drawbacks of Design Patterns
Benefits
• Design Patterns enable large-scale reuse of software architectures- They also help systems to enhance understanding
• Patterns explicitly capture expert knowledge and design tradeoffs, and make this expertise more widely available
• Patterns help improve developer communication- Pattern names form a vocabulary
• Patterns help ease the transition to object-oriented technology.
• Enable direct ruse of code
• Facilitate large amount of reuse than stand-alone functions or individual classes
Drawbacks
• Patterns do not lead to direct code reuse
• Patterns are deceptively simple
• Teams may suffer from pattern overload
• Patterns are validated by experience and discussion rather than by automated testing
• Integrating patterns into a software development process is a human-intensive activity
• High initial learning curve- Many classes and many levels of abstraction
• The flow of control for reactive dispatching is non-intuitive
• Verification and validation of generic components is hard
7. Best Practices to Design Patterns
• Do not recast everything as a pattern-Instead develop strategic domain patterns and reuse existing tactical patterns
• Institutionalize rewards for developing patterns
• Directly involve pattern authors with application developers and domain experts
• Clearly document when patterns apply and do not apply
• Manage expectations carefully
1. Introduction
A design pattern is a general repeatable solution to a commonly occurring problem in a software design.
A design pattern is an abstraction of a solution at a very high level. Many designers and architects have defined the term design patterns in various ways.
Design patterns address the recurring design problems that arise in particular design situations and propose solutions to them. Design patterns are thus successful solutions to known problems. There are various ways to implement design patterns. There implementation details are called Strategies.
A design pattern prescribes a proven solution from experienced hands for a recurring design problem. Apart from describing the problem and prescribing the solution, the pattern will also explain the implementation issues involved and consequences, if any, of using the pattern. These solutions are generic in nature. They are described in the well-defined "Pattern Templates"; the most common one in use is the template defined by the "Gang of Four." The pattern templates usually have a name that offers a good idea as to what that pattern is all about, followed by where the pattern is applicable, the motivation, implementation issues, and other descriptions.
Use of such patterns makes the design of an application transparent. These patterns have been used successfully by developers in their respective work and hence the pros and cons of their use as well as implementation issues are known beforehand. All design patterns are reusable and can be adapted to a particular context; this gives developers flexibility. The use of design patterns related to J2EE applications offer the added advantage of providing solutions for J2EE platform technologies
2. Applications of Design Patterns
They have been proven. Patterns reflect the experience, knowledge and insights of developers who have successfully used these patterns in their own work.
They are reusable. Patterns provide a readymade solution that can be adapted to different problems as necessary.
They are expressive. Patterns provide a common vocabulary of solutions that can express very large solutions succinctly.
It is important to remember that patterns do not guarantee success. A pattern description indicates when the pattern may be applicable, but only experience can provide understanding of when a particular pattern will improve a design.
3. Origin of Design Patterns
The civil engineering patterns
In the 1960s and ’70s, Christopher Alexander, professor of architecture and director of the Center for Environmental Structure, along with his colleagues, wrote a number of books describing and documenting the principles of civil engineering from a layperson’s point of view. Of them, one of the most widely known books is A Pattern Language: Towns, Buildings, and Constructions. It provides practical guidance on how to build houses, construct buildings and parking lots, design a good neighborhood, and so forth. The book examines how these simple designs integrate with each other to create well-planned towns and cities. As its title suggests, the book describes 253 patterns that are split into three broad categories: towns, buildings, and construction.
4. Design Patterns classification
The Gang of Four Patterns
Software Designers extended the idea of design patterns to software development. Since features provided by the object-oriented languages, such as inheritance, abstraction, and encapsulation, allowed them to easily relate programming language entities to real-world entities, designers started applying those features to create common and reusable solutions to recurring problems that exhibited similar patterns.
Around 1994, the now famous Gang of Four(GoF)—Erich Gamma, Richard Helm,Ralph Johnson, and John Vlissides-documented 23 such software design patterns.
They classified the patterns at the very top level into three types of categories based on their purpose ---creational, structural, and behavioral.
Creational----Creational patterns deal with the ways to create instances of objects. The objective of these patterns is to abstract the instantiation process and hide the details of how objects are created or initialized.
Structural------Structural patterns describe how classes and objects can be combined to form larger structures and provide new functionality. These aggregated objects can be either simple objects or composite objects themselves.
Behavioral----Behavioral patterns help us define the communication and interaction between the objects of a system. The purpose of these patterns is to
reduce coupling between objects.
Though the GoF patterns served well in designing and developing object-oriented systems in both distributed and non distributed environments, they were not created with the distributed nature of large-scale enterprise systems in mind. As the demands for more distributed enterprise applications grew, the architects felt the need to document the solutions to recurring problems as they experienced the same problem occurring over and over again. They started extending and refining the patterns over a larger scale and with a broader scope.
The J2EE patterns
With the advent of the J2EE, a whole new catalog of deign patterns cropped up. Since J2EE is an architecture in itself that comprises other architectures, including servlets, Java Server Pages, Enterprise Java Beans, and so forth, it deserves its own set of patterns specifically tailored to the various types of enterprise applications that the architecture addresses.
There are 5 tiers in J2EE architecture. They are
a. Client
b. Presentation
c. Business
d. Integration
e. Resource
A Tier is a logical partition of the components involved in the system. Each tier is a loosely coupled with the adjacent tier. It is easier to understand the role of design patterns once we fully grasp the different tiers involved in a J2EE application.
Client---The tier comprises all the types of components that are clients of the enterprise application. Examples of client components are a Web browser, a hand held device, or another application that accesses the services of the enterprise application remotely.
Presentation---This tier interfaces with the client tier and encapsulates the presentation logic. It accepts the requests, handles authentication and authorization, manages client sessions, delegates the business processing to the business tier, and presents the client with the defined response. The components that make up this tier are filters, servlets, Java Beans, JSP pages, and other utility classes.
Business--- This tier is the heart of the enterprise application and implements the core business services. It is normally composed of the Enterprise Java Beans components that handle all the business processing rules.
Integration--- The job of this tier is to seamlessly integrate different types of external resources in the resource tier with the components of the business tier. The components that make up the integration tier use various mechanisms like JDBC,J2EE connector technology, or proprietary middleware to access the resource tier.
Resource--- This tier comprises the external resources that provide actual data to the application. The resources can either be data sources such as relational databases and file-based databases or such as applications running on mainframes. Other legacy systems, modern business-to-business(B2B)systems, and third party services like credit card authorization services.
Each of the 15 J2EE design patterns fall in one of the five tiers.
Presentation Tier
• Decorator Filter/Intercepting Filter
• Front Controller/Front Component
• View Helper
• Composite View
• Service to Worker
• Dispatcher View
Business Tier
• Business Delegate
• Transfer Object/Replicate Object
• Session Façade/Session Entity Façade/ Distributed Façade
• Aggregate Entity
• Transfer Object Assembler
• View List Handler/Page-by-Page Iterator /Paged List
• Service Locator
Integration Layer
• Data Access Object
• Service Activator
MVC is most commonly heard name in J2EE domain is in fact not a J2EE design pattern instead it is an architecture.
1)Decorator Filter/Intercepting Filter
Context—
• Client request may have many processing needs, and the system must be able to meet them.
• The System receives requests using multiple protocols, such as HTTP,FTP, or SMTP.
• The System must authorize or authenticate some requests, while handling others directly.
• The System needs to add or remove information from requests are responses before further processing.
Example--
If you have to build an enterprise system that doubles as a web portal and corporate intranet, you need to ensure that different client requests are handled appropriately. Not only must the system block requests for secure resources, it must also check for trusted IP addresses. Further, it must ensure that responses and requested resources are compressed/decompressed and encrypted/decrypted as needed.
Solution—
The Solution is to separate request/response processing from the rest of the system by creating filters. These objects, more fully provide a standardized, replaceable means of altering requests and responses as needed.
2)Front Controller/Front Component
Context—
• Managing an application for an individual user requires a number of considerations
• Controlling the application’s view and navigation
• Performing security processing to determine which resources and services are available for the user.
• Activating system services according to user selection
• Locating and accessing available resources according to user selection
Example—
In a Web application that accepts credit card information, several steps must be completed.
• Browse the catalog
• Add items to the shopping cart
• Confirm the checkout
• Get the name and shipping address of the receiver
• Get the name and billing address and the credit card information of the payer.
The different views associated with the store are decentralized. This means that they each control their navigation function, as well as perform the tasks needed to dispatch the user’s request.
Solution—
we need a single object to manage view control, resource/service accessing, error handling and initial request processing. This object acts as a front door to the client and is called as front controller or Front Component. Among the various strategies suggested by J2EE, the two simplest ones are using a servlet or JSP as front objects. All requests will be sent to the Front Controller and each request will have an action as a parameter.
3) Service Locator
Context-
Many systems depend on distributed processing and communication. In these cases, a number of concerns must be kept in mind:
• The system needs to locate and access resources and services across networks.
• If the services or resources are unavailable, the system must create local
implementations.
• New requests to a directory service require more time and resources than
cached repetitions of previous requests.
Example—
A large company contains a number of worldwide branches and needs to maintain
communication throughout. Many different applications require access to similar
external resources, such as personnel databases and inventory listings. In this case, the system uses Java Naming and Directory Interface (JNDI) to help components find one another. But as each object accesses JNDI separately, its responsiveness slows.
Solution –
The solution is to encapsulate the process of external communication into a Service Locator. With this method, the Locator object manages all of the complexity related to locating and interfacing resources across the network. Further, to reduce the amount of time associated with making requests, they can provide request caching. Finally, if external resources have vendor-specific interfaces, this object will manage the communication complexity and make accessing the resource transparent to the user.
4) Business Delegate
Context—
In an enterprise-scaled distributed application, typically the following situation arises:
• There are separate components to interact with the end users and to handle
business logic.
• These separate components reside in different subsystems, separated by a
network.
• The components that handle the business logic act as server components
because they provide business services to the clients by exposing the business
service API to the clients.
• The client components that use this API often reside in a remote system
separated by a network.
• There is more than one client using the API.
• There is more than one server component providing similar services, but with
minor differences in the API.
Example –
Let’s look at a real-world example. A company is building a web-based application
with JSP pages and servlets that need to access a set of business services. The management has decided not to develop the business services in-house, since they are readily available as off-the-shelf software from various vendors. In addition, the budget for the project is currently tight, so management has decided that they will purchase one of the more economical off-the-shelf solutions initially, and then when the money becomes available in a year, they will replace it with a more elaborate and expensive software solution.
Solution
Create a Business Delegate to handle all of the code that accesses the business services in the selected vendor software. When the vendor changes, the only changes that need to be made to the company’s application software are changes to the Business Delegate, to access the business services in the new vendor software. The JSP pages and servlets will not have to be modified.
The responsibilities of the components participating in this pattern are
• Client components—The client components, which are JSP pages and servlets in
the presentation tier, delegate the work of locating the business service providers
and the work of invoking the business service API methods to the Business Delegate objects.
• Business Delegate—The Business Delegate acts as a representative of the client
components. It knows how to look up and access the business services. It invokes the appropriate business services methods in the required order. If the API of the business service component changes, only the Business Delegate needs to be modified, without affecting the client components.
• Business service—A business service component implements the actual business
logic. Some examples of business service components are a stateless session EJB,
an entity EJB, a CORBA object, or an RPC server.
5) Transfer Object
Context
In distributed applications, the following situation typically arises:
• The client-side and the server-side components reside at remote locations and
communicate over the network.
• The server handles the database.
• The server provides getter methods to the clients so that the clients can call
those getter methods one by one to retrieve database values.
• The server provides setter methods to the clients so that the clients can call
those setter methods one by one to update database values.
Example
In the J2EE architecture, the business tier accesses the database directly or via the resource tier, and wraps the data access mechanism inside a set of entity beans and session beans. These entity and session beans expose the data via remote interfaces. The servlets and JSP pages in the presentation tier that need to access business data can do so by calling methods on the remote interfaces implemented by the beans.
As a specific example, suppose we maintain the address information in the database of the registered users of our enterprise application. In this case, the address information, which is a summation of four other pieces of data—street, city, state, and, zip—is a business entity. The access to this information is encapsulated by the application’s business tier with the help of a session bean called AddressSessionBean. AddressSessionBean exposes methods for the remote clients, such as getState (), setState(), getCity (), and setCity(). The servlets and the JSP pages then have to call each of the methods one by one on the remote server, as shown in figure below.
Solution
Create an object to encapsulate all of the attribute values that are required by the client application. This object is called the Transfer Object. When the client requests the data from the server, the server-side component gathers the data values and constructs the Transfer Object by setting its data values. This object is then sent to the client by value (not by reference), which means that the whole object is serialized and each of its bits is transferred over the network.
The client on the other side reconstructs this object locally with all the values intact. It can then query this local instance for all the attribute values. Because the Transfer Object is local on the client, all of the calls to this object are local and do not incur any network overhead. The Transfer Object on the client serves as a proxy for the properties of the remote object. This scenario is shown in figure below.
Now, instead of making multiple remote calls on the business object, Address-
Bean, to retrieve all the attributes, the client calls a single method, getAddress(),
which returns all the attributes structured in an AddressVO object.
6) Composite View
Context
In an enterprise-scaled distributed application, typically the following situation arises:
In distributed applications, the following situation typically arises:
• The web pages present data from various data sources, using multiple sub views that comprise a single display page.
• The server handles the database.
The Server may need to be restarted before clients see the modifications are updates to the template components.
Example
In real world application web pages present content from numerous data sources, using multiple sub views that comprise a single display page. The web pages are built by embedding formatting code directly with each atomic view. Atomic portion of the view content changes frequently , modification to the layout of multiple views is difficult and error prone when sub views are directly embedded and duplicated in multiple views. Embedding frequently changing portions of template text directly into views also potentially affects the availability and administration of the system.
Solution
The solution to this is to use composite views that are composed of multiple atomic sub views. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content.
This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design. It is appropriate to use a composite view to generate pages containing display components that may be combined in a variety of ways. The layout of the page is managed and modified independent of the subview content.
The responsibilities of the components participating in these patterns are :
Composite View:--
A composite view is a view that is an aggregate of multiple subviews.
View Manager:--
The View Manager manages the inclusion of portions of template fragments into the composite view. The View Manager may be part of a standard JSP page runtime engine, in the form of the standard Java Server Pages (JSP page) pages include tag (
certain template fragments may be included only if the user fulfills a particular role or certain system conditions are satisfied. Furthermore, using a helper component as a View Manager allows for more sophisticated control of the page structure as a whole, which is useful for creating reusable page layouts.
IncludedView--
An included view is a subview that is one atomic piece of a larger whole view. This included view could also potentially be a composite, itself including multiple subviews.
7) Data Access Object
Context
Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
If the client needs to display or update a set of attributes that live on the server, these attributes could live in an entity bean or be accessible through a session bean. The client could get or update the data is by loading many parameters into a method call, when updating data on the server, or by making multiple fine-grained calls to the server to retrieve data. Every call between the client and server is a remote method call with substantial network overhead. If the client application calls the individual getter and setter methods that require or update single attribute values, it will require as many remote calls as there are attributes. The individual calls generate a lot of network traffic and affects severely the system performance.
To deal with suck kind of scenario we need to go for the DAO pattern.
Example
Suppose if the user want to send data a number of times through the program like entering user personal information or accessing just like online transactions services etc, we need to go for this approach.
Solution
The solution to this problem is to use a plain java classes called Value Objects or Transfer Objects which encapsulate the bulk business data. A single method call is used to send and retrieve the Transfer Object / Value Objects. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client.
8) Session Façade/Session Entity Façade/Distributed Facade
Context
Enterprise beans encapsulate business logic and business data and expose their interfaces, and thus the complexity of the distributed services, to the client tier.
In a multitiered Java 2 Platform, Enterprise Edition (J2EE) application environment, the following problems arise:
• Tight coupling, which leads to direct dependence between clients and business objects;
• Too many method invocations between client and server, leading to network performance problems;
• Lack of a uniform client access strategy, exposing business objects to misuse.
Example
An example demonstrating the use of Session Facade design pattern in a typical HR application.
Employees and Departments are used to store and retrieve employee and department information from the database. addition, the application allows the user to add a new department and assign existing employees to the newly added department. As this involves accessing two different entities, it should take place in one transaction. In this application only the admin user is allowed to add a new department.
Solution
Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.
The Session Facade abstracts the underlying business object interactions and provides a service layer that exposes only the required interfaces. Thus, it hides from the client's view the complex interactions between the participants. The Session Facade manages the interactions between the business data and business service objects that participate in the workflow, and it encapsulates the business logic associated with the requirements. Thus, the session bean (representing the Session Facade) manages the relationships between business objects. The session bean also manages the life cycle of these participants by creating, locating (looking up), modifying, and deleting them as required by the workflow. In a complex application, the Session Facade may delegate this lifestyle management to a separate object. For example, to manage the lifestyle of participant session and entity beans, the Session Facade may delegate that work to a Service Locator object
9) Service Activator
Context
An application has a service that it would like to make available to other applications.
Example
A Typical web application which requires the service of an authentication mechanism for a user is put in this service activator, and is invoked each time a user is login.
Solution
A Service Activator Service Activator can be one-way (request only) or two-way (Request-Reply). The service can be as simple as a method call—synchronous and non-remote—perhaps part of a Service Layer The activator can be hard-coded to always invoke the same service, or can use reflection to invoke the service indicated by the message. The activator handles all of the messaging details and invokes the service like any other client, such that the service doesn’t even know its being invoked through messaging.
The architecture of the Service Activator can be seen from the figure above.
10) Dispatcher View
Context
System controls flow of execution and access to presentation processing, which is responsible for generating dynamic content.
The Dispatcher View pattern, like the Service to Worker pattern, describes a common combination of other patterns from the catalog. Both of these macro patterns describe the combination of a controller and dispatcher with views and helpers. While describing this common structure, they emphasize related but different usage patterns.
Example
Authentication and authorization checks are completed per request. Scriptlet code within views should be minimized. Business logic should be encapsulated in components other than the view.
Control flow is relatively simple and is typically based on values encapsulated with the request.
View management logic is limited in complexity.
Solution
Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers do not delegate content retrieval to helpers, because these activities are deferred to the time of view processing. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller, a view, or a separate component.
Dispatcher View describes the combination of the Front Controller and View Helper patterns with a dispatcher component. While this pattern and the Service to Worker pattern describe a similar structure, the two patterns suggest a different division of labor among the components. The controller and the dispatcher typically have limited responsibilities, as compared to the Service to Worker pattern, since the upfront processing and view management logic are basic. Furthermore, if centralized control of the underlying resources is considered unnecessary, then the controller is removed and the dispatcher may be moved into a view.
Since the Service to Worker and Dispatcher View patterns represent a common combination of other patterns from the catalog, each warrants its own name to promote efficient communication among developers. Unlike the Service to Worker pattern, the Dispatcher View pattern suggests deferring content retrieval to the time of view processing.
In the Dispatcher View pattern, the dispatcher typically plays a limited to moderate role in view management. In the Service to Worker pattern, the dispatcher typically plays a moderate to large role in view management.
A limited role for the dispatcher occurs when no outside resources are utilized in order to choose the view. The information encapsulated in the request is sufficient to determine the view to dispatch the request.
For example:
http://some.server.com/servlet/Controller?next=login.jsp
The sole responsibility of the dispatcher component in this case is to dispatch to the view login.jsp.
An example of the dispatcher playing a moderate role is the case where the client submits a request directly to a controller with a query parameter that describes an action to be completed:
http://some.server.com/servlet/Controller?action=login
The responsibility of the dispatcher component here is to translate the logical name login into the resource name of an appropriate view, such as login.jsp, and dispatch to that view. To accomplish this translation, the dispatcher may access resources such as an XML configuration file that specifies the appropriate view to display.
On the other hand, in the Service to Worker pattern, the dispatcher might be more sophisticated. The dispatcher may invoke a business service to determine the appropriate view to display.
The shared structure of these two patterns, as mentioned above, consists of a controller working with a dispatcher, views, and helpers.
The figure above shows the class diagram that represents the Dispatcher View pattern.
11) Service to Worker
Context
The system controls flow of execution and access to business data, from which it creates presentation content.
A service to Worker pattern like the Dispatcher View pattern, describes a common combination of other patterns from the catalog. Both of these macro patterns describe the combination of controller and dispatcher with views and helpers. While describing this common structure, they emphasize related but different usage patterns.
Example
Authentication and authorization checks are completed per request. Scriptlet code within views should be minimized. Business logic should be encapsulated in components other than the view. Control flow is relatively complex and based on values from dynamic content. View management logic is relatively sophisticated, with multiple views potentially mapping to the same request.
Solution
Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers delegate content retrieval to helpers, which manage the population of the intermediate model for the view. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller or a separate component.
Service to Worker describes the combination of the Front Controller and View Helper patterns with a dispatcher component.
While this pattern and the Dispatcher View pattern describe a similar structure, the two patterns suggest a different division of labor among the components. In Service to Worker, the controller and the dispatcher have more responsibilities.
Since the Service to Worker and Dispatcher View patterns represent a common combination of other patterns from the catalog, each warrants its own name to promote efficient communication among developers. Unlike the Service to Worker pattern, the Dispatcher View pattern suggests deferring content retrieval to the time of view processing.
In the Dispatcher View pattern, the dispatcher typically plays a limited to moderate role in view management. In the Service to Worker pattern, the dispatcher typically plays a moderate to large role in view management.
A limited role for the dispatcher occurs when no outside resources are utilized in order to choose the view. The information encapsulated in the request is sufficient to determine the view to dispatch the request. For example,
http://some.server.com/servlet/Controller?next=login.jsp
The sole responsibility of the dispatcher component in this case is to dispatch to the view login.jsp.
An example of the dispatcher playing a moderate role is the case where the client submits a request directly to a controller with a query parameter that describes an action to be completed:
http://some.server.com/servlet/Controller?action=login
The responsibility of the dispatcher component here is to translate the logical name login into the resource name of an appropriate view, such as login.jsp, and dispatch to that view. To accomplish this translation, the dispatcher may access resources such as an XML configuration file that specifies the appropriate view to display.
On the other hand, in the Service to Worker pattern, the dispatcher might be more sophisticated. The dispatcher may invoke a business service to determine the appropriate view to display.
The shared structure of Service to Worker and Dispatcher View consists of a controller working with a dispatcher, views, and helpers.
The class diagram given above represents the Service to Worker pattern.
12)ViewHelper
Context
The system creates presentation content, which requires processing of dynamic business data.
Example
Business data assimilation requirements are nontrivial. Embedding business logic in the view promotes a copy-and-paste type of reuse. This causes maintenance problems and bugs because a piece of logic is reused in the same or different view by simply duplicating it in the new location. It is desirable to promote a clean separation of labor by having different individuals fulfill the roles of software developer and Web production team member.
One view is commonly used to respond to a particular business request.
Solution
A view contains formatting code, delegating its processing responsibilities to its helper classes, implemented as JavaBeans or custom tags. Helpers also store the view's intermediate data model and serve as business data adapters.
There are multiple strategies for implementing the view component. The JSP View Strategy suggests using a JSP as the view component. This is the preferred strategy, and it is the one most commonly used. The other principal strategy is the Servlet View Strategy, which utilizes a servlet as the view (see the section "Strategies" for more information).
Encapsulating business logic in a helper instead of a view makes our application more modular and facilitates component reuse. Multiple clients, such as controllers and views, may leverage the same helper to retrieve and adapt similar model state for presentation in multiple ways. The only way to reuse logic embedded in a view is by copying and pasting it elsewhere. Furthermore, copy-and-paste duplication makes a system harder to maintain, since the same bug potentially needs to be corrected in multiple places.
A signal that one may need to apply this pattern to existing code is when scriptlet code dominates the JSP view. The overriding goal when applying this pattern, then, is the partitioning of business logic outside of the view. While some logic is best encapsulated within helper objects, other logic is better placed in a centralized component that sits in front of the views and the helpers-this might include logic that is common across multiple requests, such as authentication checks or logging services.
If a separate controller is not employed in the architecture, or is not used to handle all requests, then the view component becomes the initial contact point for handling some requests. For certain requests, particularly those involving minimal processing, this scenario works fine. Typically, this situation occurs for pages that are based on static information, such as the first of a set of pages that will be served to a user to gather some information Additionally, this scenario occurs in some cases when a mechanism is employed to create composite pages .
The View Helper pattern focuses on recommending ways to partition your application responsibilities. For related discussions about issues dealing with directing client requests directly to a view.
Figure above is the class diagram representing the View Helper pattern.
13) View List Handler/Page-by-Page Iterator /Paged List
Context
This design pattern describes how to break a huge list of values into smaller pages and display the results one page at a time.
Example
In an application each user account is associated with many trade details and port folio details. Fetching all the data at once can be inefficient. It can take a long time, increase network traffic, and the user may only want to see a record or two.
Solution
Use a Page-by-Page Iterator to have a client object traverse a large list, one sublist or page of value objects at a time; each page can be as big or as small as the client desires.
Using this pattern makes the Less server-side data is transferred. More server side requests are made, The Iterator is not a robust Iterator.
The Iterator can be implemented as a Stateful Session Bean- so that it can keep the state of the Iterator for each client. It can cache the retrieved the pages which makes subsequent reads perform better.
We can use a Stateless Session Bean- as it has no state for the client; they have to specify what is wanted in each call. Cached pages are shared between clients.
Always use Value Objects for returned pages, do not return a collection of Entity Beans.
Use server side filtering to avoid unnecessary data transmitted to the client. Consider network load vs. server-side requests when determine the size of the pages.
14) Transfer Object Assembler
Context
In J2EE application, the server-side business components are implemented using session beans, entity beans, DAOs, and so forth. Application clients frequently need to access data that is composed from multiple objects.
Example
Separation of business logic is required between the client and the server-side components.
Because the model consists of distributed components, access to each component is associated with a network overhead. It is desirable to minimize the number of remote method calls over the network. The client typically needs only to obtain the model to present it to the user. If the client must interact with multiple components to construct the model on the fly, the chattiness between the client and the application increases. Such chattiness may reduce the network performance. Even if the client wants to perform an update, it usually updates only certain parts of the model and not the entire model. Clients do not need to be aware of the intricacies and dependencies in the model implementation. It is desirable to have loose coupling between the clients and the business components that implement the application model. Clients do not otherwise need to have the additional business logic required to construct the model from various business components.
Solution
Use a Transfer Object Assembler to build the required model or sub model. The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.
The Transfer Object Assembler constructs a composite Transfer Object that represents data from different business components. The Transfer Object caries the data for the model to the client in a single method call. Since the model data can be complex, it is recommended that this Transfer Object be immutable. That is, the client obtains such Transfer Objects with the sole purpose of using them for presentation and processing in a read-only manner. Clients are not allowed to make changes to the Transfer Objects.
When the client needs the model data, and if the model is represented by a single coarse-grained component (such as a Composite Entity), then the process of obtaining the model data is simple. The client simply requests the coarse-grained component for its composite Transfer Object. However, most real-world applications have a model composed of a combination of many coarse-grained and fine-grained components. In this case, the client must interact with numerous such business components to obtain all the data necessary to represent the model. The immediate drawbacks of this approach can be seen in that the clients become tightly coupled to the model implementation (model elements) and that the clients tend to make numerous remote method invocations to obtain the data from each individual component.
In some cases, a single coarse-grained component provides the model or parts of the model as a single Transfer Object (simple or composite). However, when multiple components represent the model, a single Transfer Object (simple or composite) may not represent the entire model. To represent the model, it is necessary to obtain Transfer Objects from various components and assemble them into a new composite Transfer Object. The server, not the client, should perform such "on-the-fly" construction of the model.
Figure given above shows the class diagram representing the relationships for the Transfer Object Assembler pattern.
15)Aggregate Entity
Context
Entity beans are not intended to represent every persistent object in the object model. Entity beans are better suited for coarse-grained persistent business objects.
Example
Entity beans are best implemented as coarse-grained objects due to the high overhead associated with each entity bean. Each entity bean is associated with an EJB home, remote object, bean implementation, and primary key, and each is managed by the container services.
Applications that directly map relational database schema to entity beans (where each row in a table is represented by an entity bean instance) tend to have a large number of fine-grained entity beans. It is desirable to keep the entity beans coarse-grained and reduce the number of entity beans in the application.
Solution
Use Aggregate Entity bean to model, represent, and manage a set of inter-related persistent objects rather than representing them as individual fine-grained entity beans. An Aggregate Entity bean represents a tree of objects.
To understand aggregation in the context of this pattern, one must first understand persistent objects and their relationships in an application. A persistent object is an object that is stored in some type of data store. Multiple clients usually share persistent objects.
Persistent objects can be classified into two types: coarse-grained objects and dependent objects.
A coarse-grained object is self-sufficient. It has its own life cycle and manages its relationships to other objects. Each coarse-grained object may reference or contain one or more other objects. The coarse-grained object usually manages the life cycles of these objects. Hence, these objects are called dependent objects. A dependent object can be a simple self-contained object or may in turn contain other dependent objects.
The life cycle of a dependent object is tightly coupled to the life cycle of the coarse-grained object. A client may only indirectly access a dependent object through the coarse-grained object. That is, dependent objects are not directly exposed to clients because their parent (coarse-grained) object manages them. Dependent objects cannot exist by themselves. Instead, they always need to have their coarse-grained (or parent) object to justify their existence.
Typically, you can view the relationship between a coarse-grained object and its dependent objects as a tree. The coarse-grained object is the root of the tree (the root node). Each dependent object can be a standalone dependent object (a leaf node) that is a child of the coarse-grained object. Or, the dependent object can have parent-child relationships with other dependent objects, in which case it is considered a branch node.
An Aggregate Entity bean can represent a coarse-grained object and all its related dependent objects. Aggregation combines inter-related persistent objects into a single entity bean, thus drastically reducing the number of entity beans required by the application. This leads to a highly coarse-grained entity bean that can better leverage the benefits of entity beans than fine-grained entity beans.
Without the Aggregate Entity approach, there is a tendency to view each coarse-grained and dependent object as a separate entity bean, leading to a large number of entity beans.
While there are many strategies in implementing the Aggregate Entity pattern, the first one we discuss is represented in the following class diagram. Here the Aggregate Entity contains the coarse-grained object, and the coarse-grained object contains dependent objects.
While there are many strategies in implementing the Aggregate Entity pattern, the first one we discuss is represented in the following class diagram. Here the Aggregate Entity contains the coarse-grained object, and the coarse-grained object contains dependent objects.
The Diagram above shows the Class diagram for the Aggregate Entity Design Pattern.
.
5. Anti Patterns
Anti patterns also called pitfalls, are classes of commonly reinvented bad solutions to problems. Anti-patterns are natural counterparts or follow-on to the study of design patterns. Programmers should try to avoid anti-patterns whenever possible, which requires diagnosing them as early as possible in the software life cycle.
6. Benefits and Drawbacks of Design Patterns
Benefits
• Design Patterns enable large-scale reuse of software architectures- They also help systems to enhance understanding
• Patterns explicitly capture expert knowledge and design tradeoffs, and make this expertise more widely available
• Patterns help improve developer communication- Pattern names form a vocabulary
• Patterns help ease the transition to object-oriented technology.
• Enable direct ruse of code
• Facilitate large amount of reuse than stand-alone functions or individual classes
Drawbacks
• Patterns do not lead to direct code reuse
• Patterns are deceptively simple
• Teams may suffer from pattern overload
• Patterns are validated by experience and discussion rather than by automated testing
• Integrating patterns into a software development process is a human-intensive activity
• High initial learning curve- Many classes and many levels of abstraction
• The flow of control for reactive dispatching is non-intuitive
• Verification and validation of generic components is hard
7. Best Practices to Design Patterns
• Do not recast everything as a pattern-Instead develop strategic domain patterns and reuse existing tactical patterns
• Institutionalize rewards for developing patterns
• Directly involve pattern authors with application developers and domain experts
• Clearly document when patterns apply and do not apply
• Manage expectations carefully
Core Java 1
| Q: | |
| A: | With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. |
|
|
| Q: | |
| A: | The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help. |
|
|
| Q: | |
| A: | Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. |
|
|
| Q: | |
| A: | Map is Interface and Hashmap is class that implements that. |
|
|
| Q: | |
| A: | The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized. |
|
|
| Q: | |
| A: | Vector is synchronized whereas arraylist is not. |
|
|
| Q: | |
| A: | AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT. |
|
|
| Q: | |
| A: | A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. |
|
|
| Q: | |
| A: | Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator. |
|
|
| Q: | |
| A: | Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. |
|
|
| Q: | |
| A: | Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass. |
|
|
| Q: | |
| A: | A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). |
Subscribe to:
Comments (Atom)