Design Patterns in Java
Design Patterns in Java
Now, a question will be arising in your mind what kind of specific problem?
Let me explain by taking an example.
Problem Given:
Suppose you want to create a class for which only a single instance (or
object) should be created and that single object can be used by all other
classes.
Solution:
Singleton design pattern is the best solution of above specific problem.
So, every design pattern has some specification or set of rules for
solving the problems. What are those specifications, you will see later in
the types of design patterns.
By using the design patterns you can make your code more flexible,
reusable and maintainable. It is the most important part because java
internally follows design patterns.
ADVERTISEMENT BY ADRECOVER
1. import java.io.*;
2. abstract class Plan{
3. protected double rate;
4. abstract void getRate();
5.
6. public void calculateBill(int units){
7. System.out.println(units*rate);
8. }
9. }//end of Plan class.
Step 2: Create the concrete classes that extends Plan abstract class.
1. class GetPlanFactory{
2.
3. //use getPlan method to get object of type Plan
4. public Plan getPlan(String planType){
5. if(planType == null){
6. return null;
7. }
8. if(planType.equalsIgnoreCase("DOMESTICPLAN")) {
9. return new DomesticPlan();
10. }
11. else if(planType.equalsIgnoreCase("COMMERCIALPLAN
")){
12. return new CommercialPlan();
13. }
14. else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
15. return new InstitutionalPlan();
16. }
17. return null;
18. }
19. }//end of GetPlanFactory class.
1. import java.io.*;
2. class GenerateBill{
3. public static void main(String args[])throws IOException{
4. GetPlanFactory planFactory = new GetPlanFactory();
5.
6. System.out.print("Enter the name of plan for which the bill will be gene
rated: ");
7. BufferedReader br=new BufferedReader(new InputStreamRead
er(System.in));
8.
9. String planName=br.readLine();
10. System.out.print("Enter the number of units for bill will be calculated: "
);
11. int units=Integer.parseInt(br.readLine());
12.
13. Plan p = planFactory.getPlan(planName);
14. //call getRate() method and calculateBill()method of DomesticPaln.
15.
16. System.out.print("Bill amount for "+planName+" of "+units+" units is
: ");
17. p.getRate();
18. p.calculateBill(units);
19. }
20. }//end of GenerateBill class.
ADVERTISEMENT BY ADRECOVER
1. import java.io.*;
2. interface Bank{
3. String getBankName();
4. }
Step 4: Create concrete classes that extend the Loan abstract class..
1. class FactoryCreator {
2. public static AbstractFactory getFactory(String choice){
3. if(choice.equalsIgnoreCase("Bank")){
4. return new BankFactory();
5. } else if(choice.equalsIgnoreCase("Loan")){
6. return new LoanFactory();
7. }
8. return null;
9. }
10.}//End of the FactoryCreator.
1. import java.io.*;
2. class AbstractFactoryPatternExample {
3. public static void main(String args[])throws IOException {
4.
5. BufferedReader br=new BufferedReader(new InputStreamRead
er(System.in));
6.
7. System.out.print("Enter the name of Bank from where you want
to take loan amount: ");
8. String bankName=br.readLine();
9.
10.System.out.print("\n");
11. System.out.print("Enter the type of loan e.g. home loan or bus
iness loan or education loan : ");
12.
13. String loanName=br.readLine();
14.AbstractFactory bankFactory = FactoryCreator.getFactory("Bank");
15. Bank b=bankFactory.getBank(bankName);
16.
17. System.out.print("\n");
18.System.out.print("Enter the interest rate for "+b.getBankName()+ ": ");
19.
20.double rate=Double.parseDouble(br.readLine());
21. System.out.print("\n");
22.System.out.print("Enter the loan amount you want to take: ");
23.
24.double loanAmount=Double.parseDouble(br.readLine());
25. System.out.print("\n");
26.System.out.print("Enter the number of years to pay your entire loan amou
nt: ");
27. int years=Integer.parseInt(br.readLine());
28.
29. System.out.print("\n");
30.System.out.println("you are taking the loan from "+ b.getBankName());
31.
32.AbstractFactory loanFactory = FactoryCreator.getFactory("Loan");
33. Loan l=loanFactory.getLoan(loanName);
34. l.getInterestRate(rate);
35. l.calculateLoanPayment(loanAmount,years);
36. }
37. }//End of the AbstractFactoryPatternExample
Singleton Pattern says that just"define a class that has only one
instance and provides a global point of access to it".
In other words, a class must ensure that only single instance should be
created and single object can be used by all other classes.
ADVERTISEMENT BY ADRECOVER
Usage of Singleton design pattern
o Singleton pattern is mostly used in multi-threaded and database
applications. It is used in logging, caching, thread pools, configuration
settings etc.
In such case, we create the instance of the class at the time of declaring
the static data member, so instance of the class is created at the time of
classloading.
File: A.java
1. class A{
2. private static A obj=new A();//Early, instance will be created at load tim
e
3. private A(){}
4.
5. public static A getA(){
6. return obj;
7. }
8.
9. public void doSomething(){
10. //write your code
11. }
12.}
Let's see the simple example of singleton design pattern using lazy
instantiation.
File: A.java
1. class A{
2. private static A obj;
3. private A(){}
4.
5. public static A getA(){
6. if (obj == null){
7. synchronized(Singleton.class){
8. if (obj == null){
9. obj = new Singleton();//instance will be created at request ti
me
10. }
11. }
12. }
13. return obj;
14. }
15.
16. public void doSomething(){
17. //write your code
18. }
19. }
File: JDBCSingleton.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.PreparedStatement;
7. import java.sql.ResultSet;
8. import java.sql.SQLException;
9.
10.class JDBCSingleton {
11. //Step 1
12. // create a JDBCSingleton class.
13. //static member holds only one instance of the JDBCSinglet
on class.
14.
15. private static JDBCSingleton jdbc;
16.
17. //JDBCSingleton prevents the instantiation from any other c
lass.
18. private JDBCSingleton() { }
19.
20. //Now we are providing gloabal point of access.
21. public static JDBCSingleton getInstance() {
22. if (jdbc==null)
23. {
24. jdbc=new JDBCSingleton();
25. }
26. return jdbc;
27. }
28.
29. // to get the connection from methods like insert, view etc.
30. private static Connection getConnection()throws ClassNotFoundE
xception, SQLException
31. {
32.
33. Connection con=null;
34. Class.forName("com.mysql.jdbc.Driver");
35. con= DriverManager.getConnection("jdbc:mysql://
localhost:3306/ashwanirajput", "root", "ashwani");
36. return con;
37.
38. }
39.
40. //to insert the record into the database
41. public int insert(String name, String pass) throws SQL
Exception
42. {
43. Connection c=null;
44.
45. PreparedStatement ps=null;
46.
47. int recordCounter=0;
48.
49. try {
50.
51. c=this.getConnection();
52. ps=c.prepareStatement("insert into userdata(uname,upassw
ord)values(?,?)");
53. ps.setString(1, name);
54. ps.setString(2, pass);
55. recordCounter=ps.executeUpdate();
56.
57. } catch (Exception e) { e.printStackTrace(); } finally
{
58. if (ps!=null){
59. ps.close();
60. }if(c!=null){
61. c.close();
62. }
63. }
64. return recordCounter;
65. }
66.
67. //to view the data from the database
68. public void view(String name) throws SQLException
69. {
70. Connection con = null;
71. PreparedStatement ps = null;
72. ResultSet rs = null;
73.
74. try {
75.
76. con=this.getConnection();
77. ps=con.prepareStatement("select * from userd
ata where uname=?");
78. ps.setString(1, name);
79. rs=ps.executeQuery();
80. while (rs.next()) {
81. System.out.println("Name= "+rs.getStrin
g(2)+"\t"+"Paasword= "+rs.getString(3));
82.
83. }
84.
85. } catch (Exception e) { System.out.println(e);}
86. finally{
87. if(rs!=null){
88. rs.close();
89. }if (ps!=null){
90. ps.close();
91. }if(con!=null){
92. con.close();
93. }
94. }
95. }
96.
97. // to update the password for the given username
98. public int update(String name, String password) throws SQLExceptio
n {
99. Connection c=null;
100. PreparedStatement ps=null;
101.
102. int recordCounter=0;
103. try {
104. c=this.getConnection();
105. ps=c.prepareStatement(" update userdata set u
password=? where uname='"+name+"' ");
106. ps.setString(1, password);
107. recordCounter=ps.executeUpdate();
108. } catch (Exception e) { e.printStackTrace(); } finally{
109.
110. if (ps!=null){
111. ps.close();
112. }if(c!=null){
113. c.close();
114. }
115. }
116. return recordCounter;
117. }
118.
119. // to delete the data from the database
120. public int delete(int userid) throws SQLException{
121. Connection c=null;
122. PreparedStatement ps=null;
123. int recordCounter=0;
124. try {
125. c=this.getConnection();
126. ps=c.prepareStatement(" delete from userdata where
uid='"+userid+"' ");
127. recordCounter=ps.executeUpdate();
128. } catch (Exception e) { e.printStackTrace(); }
129. finally{
130. if (ps!=null){
131. ps.close();
132. }if(c!=null){
133. c.close();
134. }
135. }
136. return recordCounter;
137. }
138. }// End of JDBCSingleton class
File: JDBCSingletonDemo.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.PreparedStatement;
7. import java.sql.ResultSet;
8. import java.sql.SQLException;
9. class JDBCSingletonDemo{
10. static int count=1;
11. static int choice;
12. public static void main(String[] args) throws IOException {
13.
14. JDBCSingleton jdbc= JDBCSingleton.getInstance();
15.
16.
17. BufferedReader br=new BufferedReader(new InputStrea
mReader(System.in));
18. do{
19. System.out.println("DATABASE OPERATIONS");
20. System.out.println(" --------------------- ");
21. System.out.println(" 1. Insertion ");
22. System.out.println(" 2. View ");
23. System.out.println(" 3. Delete ");
24. System.out.println(" 4. Update ");
25. System.out.println(" 5. Exit ");
26.
27. System.out.print("\n");
28. System.out.print("Please enter the choice what you want to perform i
n the database: ");
29.
30. choice=Integer.parseInt(br.readLine());
31. switch(choice) {
32.
33. case 1:{
34. System.out.print("Enter the username you want to insert data
into the database: ");
35. String username=br.readLine();
36. System.out.print("Enter the password you want to insert data
into the database: ");
37. String password=br.readLine();
38.
39. try {
40. int i= jdbc.insert(username, password);
41. if (i>0) {
42. System.out.println((count++) + " Data has been inserte
d successfully");
43. }else{
44. System.out.println("Data has not been inserted ");
45. }
46.
47. } catch (Exception e) {
48. System.out.println(e);
49. }
50.
51. System.out.println("Press Enter key to continue...
");
52. System.in.read();
53.
54. }//End of case 1
55. break;
56. case 2:{
57. System.out.print("Enter the username : ");
58. String username=br.readLine();
59.
60. try {
61. jdbc.view(username);
62. } catch (Exception e) {
63. System.out.println(e);
64. }
65. System.out.println("Press Enter key to continue...
");
66. System.in.read();
67.
68. }//End of case 2
69. break;
70. case 3:{
71. System.out.print("Enter the userid, you want to
delete: ");
72. int userid=Integer.parseInt(br.readLine());
73.
74. try {
75. int i= jdbc.delete(userid);
76. if (i>0) {
77. System.out.println((count++) + " Data has b
een deleted successfully");
78. }else{
79. System.out.println("Data has not been del
eted");
80. }
81.
82. } catch (Exception e) {
83. System.out.println(e);
84. }
85. System.out.println("Press Enter key to continue...
");
86. System.in.read();
87.
88. }//End of case 3
89. break;
90. case 4:{
91. System.out.print("Enter the username, you want
to update: ");
92. String username=br.readLine();
93. System.out.print("Enter the new password ");
94. String password=br.readLine();
95.
96. try {
97. int i= jdbc.update(username, password);
98. if (i>0) {
99. System.out.println((count++) + " Data has b
een updated successfully");
100. }
101.
102. } catch (Exception e) {
103. System.out.println(e);
104. }
105. System.out.println("Press Enter key to continue...
");
106. System.in.read();
107.
108. }// end of case 4
109. break;
110.
111. default:
112. return;
113. }
114.
115. } while (choice!=4);
116. }
117. }
ADVERTISEMENT BY ADRECOVER
UML for Prototype Pattern
1. interface Prototype {
2.
3. public Prototype getClone();
4.
5. }//End of Prototype interface.
File: EmployeeRecord.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4.
5. class PrototypeDemo{
6. public static void main(String[] args) throws IOException {
7.
8. BufferedReader br =new BufferedReader(new InputStreamReader(S
ystem.in));
9. System.out.print("Enter Employee Id: ");
10. int eid=Integer.parseInt(br.readLine());
11. System.out.print("\n");
12.
13. System.out.print("Enter Employee Name: ");
14. String ename=br.readLine();
15. System.out.print("\n");
16.
17. System.out.print("Enter Employee Designation: ");
18. String edesignation=br.readLine();
19. System.out.print("\n");
20.
21. System.out.print("Enter Employee Address: ");
22. String eaddress=br.readLine();
23. System.out.print("\n");
24.
25. System.out.print("Enter Employee Salary: ");
26. double esalary= Double.parseDouble(br.readLine());
27. System.out.print("\n");
28.
29. EmployeeRecord e1=new EmployeeRecord(eid,ename,e
designation,esalary,eaddress);
30.
31. e1.showRecord();
32. System.out.println("\n");
33. EmployeeRecord e2=(EmployeeRecord) e1.getClone();
34. e2.showRecord();
35. }
36.}//End of the ProtoypeDemo class.
It is mostly used when object can't be created in single step like in the de-
serialization of a complex object.
File: CD.java
1. import java.util.ArrayList;
2. import java.util.List;
3. public class CDType {
4. private List<Packing> items=new ArrayList<Packing>();
5. public void addItem(Packing packs) {
6. items.add(packs);
7. }
8. public void getCost(){
9. for (Packing packs : items) {
10. packs.price();
11. }
12. }
13. public void showItems(){
14. for (Packing packing : items){
15. System.out.print("CD name : "+packing.pack());
16. System.out.println(", Price : "+packing.price());
17. }
18. }
19. }//End of the CDType class.
5) Create the CDBuilder class
File: CDBuilder.java
Pizza can be either a Veg pizza or Non-Veg pizza of several types (like
cheese pizza, onion pizza, masala-pizza etc) and will be of 4 sizes i.e.
small, medium, large, extra-large.
Cold-drink can be of several types (like Pepsi, Coke, Dew, Sprite, Fanta,
Maaza, Limca, Thums-up etc.) and will be of 3 sizes small, medium, large.
Real world example of builder pattern
Let's see the step by step real world example of Builder Design Pattern.
File: Item.java
File: Pizza.java
File: ColdDrink.java
File: VegPizza.java
File: NonVegPizza.java
File: SmallCheezePizza.java
File: SmallOnionPizza.java
File: SmallMasalaPizza.java
File: SmallNonVegPizza.java
File: Pepsi.java
File: SmallCoke.java
File: OrdereBuilder.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class OrderBuilder {
5. public OrderedItems preparePizza() throws IOException{
6.
7. OrderedItems itemsOrder=new OrderedItems();
8. BufferedReader br =new BufferedReader(new InputStreamReader(S
ystem.in));
9.
10. System.out.println(" Enter the choice of Pizza ");
11. System.out.println("======================
======");
12. System.out.println(" 1. Veg-Pizza ");
13. System.out.println(" 2. Non-Veg Pizza ");
14. System.out.println(" 3. Exit ");
15. System.out.println("======================
======");
16.
17. int pizzaandcolddrinkchoice=Integer.parseInt(br.readLin
e());
18. switch(pizzaandcolddrinkchoice)
19. {
20. case 1:{
21.
22. System.out.println("You ordered Veg Pizza");
23. System.out.println("\n\n");
24. System.out.println(" Enter the types of Veg-Pizza ");
25. System.out.println("------------------------------");
26. System.out.println(" 1.Cheeze Pizza ");
27. System.out.println(" 2.Onion Pizza ");
28. System.out.println(" 3.Masala Pizza ");
29. System.out.println(" 4.Exit ");
30. System.out.println("------------------------------");
31. int vegpizzachoice=Integer.parseInt(br.r
eadLine());
32. switch(vegpizzachoice)
33. {
34. case 1:
35. {
36. System.out.println("You ordered Cheeze Pizza");
37.
38. System.out.println("Enter the cheeze pizza size");
39. System.out.println("---------------------------
---------");
40. System.out.println(" 1. Small Cheeze Pizza ");
41. System.out.println(" 2. Medium Cheez
e Pizza ");
42. System.out.println(" 3. Large Cheeze Pizza ");
43. System.out.println(" 4. Extra-Large Ch
eeze Pizza ");
44. System.out.println("------------------------------------");
45. int cheezepizzasize=Integer.parseInt(b
r.readLine());
46. switch(cheezepizzasize)
47. {
48. case 1:
49. itemsOrder.addItems(new Sm
allCheezePizza());
50. break;
51. case 2:
52. itemsOrder.addItems(new MediumCheeze
Pizza());
53. break;
54. case 3:
55. itemsOrder.addItems(new Lar
geCheezePizza());
56. break;
57. case 4:
58. itemsOrder.addItems(new ExtraLargeChe
ezePizza());
59. break;
60. case 2:
61. {
62. System.out.println("You ordered Onion Pizza");
63. System.out.println("Enter the Onion piz
za size");
64. System.out.println("----------------------------------");
65. System.out.println(" 1. Small Onion Pi
zza ");
66. System.out.println(" 2. Medium Onion Pizza ");
67. System.out.println(" 3. Large Onion Pi
zza ");
68. System.out.println(" 4. Extra-Large Onion Pizza ");
69. System.out.println("---------------------------
-------");
70. int onionpizzasize=Integer.parseInt(br.readLine());
71. switch(onionpizzasize)
72. {
73. case 1:
74. itemsOrder.addItems(new SmallOnionPizz
a());
75. break;
76.
77. case 2:
78. itemsOrder.addItems(new MediumOnionPi
zza());
79. break;
80.
81. case 3:
82. itemsOrder.addItems(new LargeOnionPizz
a());
83. break;
84.
85. case 4:
86. itemsOrder.addItems(new ExtraLargeOnio
nPizza());
87. break;
88.
89. }
90. }
91. break;
92. case 3:
93. {
94. System.out.println("You ordered Masala Pizza");
95. System.out.println("Enter the Masala pi
zza size");
96. System.out.println("------------------------------------");
97. System.out.println(" 1. Small Masala P
izza ");
98. System.out.println(" 2. Medium Masala Pizza ");
99. System.out.println(" 3. Large Masala
Pizza ");
100. System.out.println(" 4. Extra-Large Masala
Pizza ");
101. System.out.println("---------------------------
---------");
102. int masalapizzasize=Integer.parseIn
t(br.readLine());
103. switch(masalapizzasize)
104. {
105. case 1:
106. itemsOrder.addItems(new SmallMa
salaPizza());
107. break;
108.
109. case 2:
110. itemsOrder.addItems(new Medium
MasalaPizza());
111. break;
112.
113. case 3:
114. itemsOrder.addItems(new LargeMa
salaPizza());
115. break;
116.
117. case 4:
118. itemsOrder.addItems(new ExtraLar
geMasalaPizza());
119. break;
120.
121. }
122.
123. }
124. break;
125.
126. }
127.
128. }
129. break;// Veg- pizza choice completed.
130.
131. case 2:
132. {
133. System.out.println("You ordered Non-Veg Pizza
");
134. System.out.println("\n\n");
135.
136. System.out.println("Enter the Non-Veg pizza
size");
137. System.out.println("---------------------------
---------");
138. System.out.println(" 1. Small Non-Veg Pizz
a ");
139. System.out.println(" 2. Medium Non-
Veg Pizza ");
140. System.out.println(" 3. Large Non-Veg Pizz
a ");
141. System.out.println(" 4. Extra-Large No
n-Veg Pizza ");
142. System.out.println("-----------------------------------
-");
143.
144.
145. int nonvegpizzasize=Integer.parseInt(br.readLi
ne());
146.
147. switch(nonvegpizzasize)
148. {
149.
150. case 1:
151. itemsOrder.addItems(new SmallNonV
egPizza());
152. break;
153.
154. case 2:
155. itemsOrder.addItems(new MediumNo
nVegPizza());
156. break;
157.
158. case 3:
159. itemsOrder.addItems(new LargeNonV
egPizza());
160. break;
161.
162. case 4:
163. itemsOrder.addItems(new ExtraLarge
NonVegPizza());
164. break;
165. }
166.
167. }
168. break;
169. default:
170. {
171. break;
172.
173. }
174.
175. }//end of main Switch
176.
177. //continued?..
178. System.out.println(" Enter the choice of ColdDrink ");
179. System.out.println("======================
======");
180. System.out.println(" 1. Pepsi ");
181. System.out.println(" 2. Coke ");
182. System.out.println(" 3. Exit ");
183. System.out.println("======================
======");
184. int coldDrink=Integer.parseInt(br.readLine());
185. switch (coldDrink)
186. {
187. case 1:
188. {
189. System.out.println("You ordered Pepsi "
);
190. System.out.println("Enter the Pepsi Size ");
191. System.out.println("------------------------");
223. System.out.println("------------------------");
224.
225. int cokesize=Integer.parseInt(br.readLi
ne());
226. switch(cokesize)
227. {
228. case 1:
229. itemsOrder.addItems(new Sm
allCoke());
230. break;
231.
232. case 2:
233. itemsOrder.addItems(new Me
diumCoke());
234. break;
235.
236. case 3:
237. itemsOrder.addItems(new Lar
geCoke());
238. break;
239.
240.
241. }
242.
243. }
244. break;
245. default:
246. {
247. break;
248.
249. }
250.
251. }//End of the Cold-Drink switch
252. return itemsOrder;
253.
254. } //End of the preparePizza() method
File: Prototype.java
1. import java.io.IOException;
2. public class BuilderDemo {
3.
4. public static void main(String[] args) throws IOException {
5. // TODO code application logic here
6.
7. OrderBuilder builder=new OrderBuilder();
8.
9. OrderedItems orderedItems=builder.preparePizza();
10.
11. orderedItems.showItems();
12.
13. System.out.println("\n");
14. System.out.println("Total Cost : "+ orderedItems.getCost());
15.
16. }
17. }// End of the BuilderDemo class
Object Pool Pattern says that " to reuse the object that are expensive
to create".
Usage:
o When an application requires objects which are expensive to create. Eg:
there is a need of opening too many connections for the database then it
takes too longer to create a new one and the database server will be
overloaded.
o When there are several clients who need the same resource at different
times.
ADVERTISEMENT BY ADRECOVER
NOTE: Object pool design pattern is essentially used in Web Container of the
server for creating thread pools and data source pools to process the requests.
File: ObjectPool.java
1. import java.util.concurrent.ConcurrentLinkedQueue;
2. import java.util.concurrent.Executors;
3. import java.util.concurrent.ScheduledExecutorService;
4. import java.util.concurrent.TimeUnit;
5.
6. public abstract class ObjectPool<T> {
7. /*
8. pool implementation is based on ConcurrentLinkedQueue from the java.u
til.concurrent package.
9. ConcurrentLinkedQueue is a thread-safe queue based on linked no
des.
10. Because the queue follows FIFO technique (first-in-first-out).
11. */
12.
13. private ConcurrentLinkedQueue<T> pool;
14.
15. /*
16.
17. ScheduledExecutorService starts a special task in a separate
thread and observes
18. the minimum and maximum number of objects in the pool periodically in
a specified
19. time (with parameter validationInterval).
20. When the number of objects is less than the minimum, missing instances
will be created.
21. When the number of objects is greater than the maximum, t
oo many instances will be removed.
22. This is sometimes useful for the balance of memory consuming objects i
n the pool.
23. */
24. private ScheduledExecutorService executorService;
25. /*
26. * Creates the pool.
27. *
28. * @param minObjects : the minimum number of objects residing in the
pool
29. */
30.
31. public ObjectPool(final int minObjects)
32. {
33. // initialize pool
34.
35. initialize(minObjects);
36.
37. }
38.
39. /*
40. Creates the pool.
41. @param minObjects: minimum number of objects residin
g in the pool.
42. @param maxObjects: maximum number of objects residing in the po
ol.
43. @param validationInterval: time in seconds for periodical c
hecking of
44. minObjects / maxObjects conditions in a separate thread.
45. When the number of objects is less than minObjects, missi
ng instances will be created.
46. When the number of objects is greater than maxObjects, too many inst
ances will be removed.
47. */
48. public ObjectPool(final int minObjects, final int maxObjects, final lo
ng validationInterval) {
49. // initialize pool
50. initialize(minObjects);
51. // check pool conditions in a separate thread
52. executorService = Executors.newSingleThreadScheduledExecutor();
53. executorService.scheduleWithFixedDelay(new Runnable(
) // annonymous class
54. {
55. @Override
56. public void run() {
57. int size = pool.size();
58.
59. if (size < minObjects) {
60. int sizeToBeAdded = minObjects + size;
61. for (int i = 0; i < sizeToBeAdded; i++) {
62. pool.add(createObject());
63. }
64. } else if (size > maxObjects) {
65. int sizeToBeRemoved = size - maxObjects;
66. for (int i = 0; i < sizeToBeRemoved; i++) {
67. pool.poll();
68. }
69. }
70. }
71. }, validationInterval, validationInterval, TimeUnit.SECON
DS);
72. }
73.
74. /*
75. Gets the next free object from the pool. If the pool doesn't
contain any objects,
76. a new object will be created and given to the caller of this method bac
k.
77.
78. @return T borrowed object
79. */
80. public T borrowObject() {
81. T object;
82. if ((object = pool.poll()) == null)
83. {
84. object = createObject();
85. }
86. return object;
87. }
88. /*
89. Returns object back to the pool.
90. @param object object to be returned
91. */
92. public void returnObject(T object) {
93. if (object == null) {
94. return;
95. }
96. this.pool.offer(object);
97. }
98. /*
99. Shutdown this pool.
100. */
101. public void shutdown(){
102. if (executorService != null){
103. executorService.shutdown();
104. }
105. }
106. /*
107. Creates a new object.
108. @return T new object
109. */
110. protected abstract T createObject();
111.
112. private void initialize(final int minObjects) {
113. pool = new ConcurrentLinkedQueue<T>();
114. for (int i = 0; i < minObjects; i++) {
115. pool.add(createObject());
116. }
117. }
118. }// End of the ObjectPool Class.
Step 2
File: ExportingProcess.java
File: ExportingTask.java
File: ObjectPoolDemo.java
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. import java.util.concurrent.TimeUnit;
4. import java.util.concurrent.atomic.AtomicLong;
5. public class ObjectPoolDemo{
6. private ObjectPool<ExportingProcess> pool;
7. private AtomicLong processNo=new AtomicLong(0);
8. public void setUp() {
9. // Create a pool of objects of type ExportingProcess.
10. /*Parameters:
11. 1) Minimum number of special ExportingProcess insta
nces residing in the pool = 4
12. 2) Maximum number of special ExportingProcess instances residin
g in the pool = 10
13. 3) Time in seconds for periodical checking of minObje
cts / maxObjects conditions
14. in a separate thread = 5.
15. -->When the number of ExportingProcess instances is
less than minObjects,
16. missing instances will be created.
17. -->When the number of ExportingProcess instances is
greater than maxObjects,
18. too many instances will be removed.
19. -->If the validation interval is negative, no periodical c
hecking of
20. minObjects / maxObjects conditions in a separate thread take
place.
21. These boundaries are ignored then.
22. */
23. pool = new ObjectPool<ExportingProcess>(4, 10, 5)
24. {
25. protected ExportingProcess createObject()
26. {
27. // create a test object which takes some time for cre
ation
28. return new ExportingProcess( processNo.incrementAndGet());
29. }
30. };
31. }
32. public void tearDown() {
33. pool.shutdown();
34. }
35. public void testObjectPool() {
36. ExecutorService executor = Executors.newFixedThreadPool(8);
37.
38. // execute 8 tasks in separate threads
39.
40. executor.execute(new ExportingTask(pool, 1));
41. executor.execute(new ExportingTask(pool, 2));
42. executor.execute(new ExportingTask(pool, 3));
43. executor.execute(new ExportingTask(pool, 4));
44. executor.execute(new ExportingTask(pool, 5));
45. executor.execute(new ExportingTask(pool, 6));
46. executor.execute(new ExportingTask(pool, 7));
47. executor.execute(new ExportingTask(pool, 8));
48.
49. executor.shutdown();
50. try {
51. executor.awaitTermination(30, TimeUnit.SECONDS);
52. } catch (InterruptedException e)
53.
54. {
55. e.printStackTrace();
56. }
57. }
58. public static void main(String args[]) {
59. ObjectPoolDemo op=new ObjectPoolDemo();
60. op.setUp();
61. op.tearDown();
62. op.testObjectPool();
63. }
64.}//End of the ObjectPoolDemo class.
These patterns focus on, how the classes inherit from each other and how
they are composed from other classes.
1. Adapter Pattern
2. Bridge Pattern
3. Composite Pattern
4. Decorator Pattern
5. Facade Pattern
6. Flyweight Pattern
7. proxy Pattern
It is used:
ADVERTISEMENT BY ADRECOVER
o Target Interface: This is the desired interface class which will be used by
the clients.
o Adapter class: This class is a wrapper class which implements the
desired target interface and modifies the specific request available from
the Adaptee class.
o Adaptee class: This is the class which is used by the Adapter class to
reuse the existing functionality and modify them for desired use.
o Client: This class will interact with the Adapter class.
File: BankDetails.java
File: BankCustomer.java
File: AdapterPatternDemo.java
Bridge Pattern
1. Bridge Design Pattern
2. Advantage of Bridge DP
3. Usage of Bridge DP
4. UML of Bridge DP
5. Example of Bridge DP
ADVERTISEMENT BY ADRECOVER
1. --------------------------------------------------------------------
2. Question Paper: Java Programming Language
3. What is class?
4. What is interface?
5. What is abstraction?
6. How multiple polymorphism is achieved in java?
7. How many types of exception handling are there in java?
8. Define the keyword final for variable, method, and class in java?
9. What is abstract class?
10. What is multi-threading?
11. What is inheritance?
12. How many types of inheritance are there in java?
13. -----------------------------------------------------------------------
Composite Pattern
1. Composite Design Pattern
2. Advantage of Composite DP
3. Usage of Composite DP
4. UML of Composite DP
5. Example of Composite DP
It is used:
ADVERTISEMENT BY ADRECOVER
1) Component
2) Leaf
3) Composite
4) Client
Client uses the component class interface to interact with objects in the
composition structure. If recipient is the leaf then request will be handled
directly. If recipient is a composite, then it usually forwards the request to
its child for performing the additional operations.
File: BankManager.java
Create a Cashier class that will be treated as a leaf and it will implement
to the Employee interface.
File: Cashier.java
Create a Accountant class that will also be treated as a leaf and it will
implement to the Employee interface.
File: Accountant.java
File: CompositePatternDemo.java
Decorator Pattern
1. Decorator Design Pattern
2. Advantage of Decorator DP
3. Usage of Decorator DP
4. UML of Decorator DP
5. Example of Decorator DP
A Decorator Pattern says that just "attach a flexible additional
responsibilities to an object dynamically".
It is used:
ADVERTISEMENT BY ADRECOVER
UML for Decorator Pattern:
Step 2: Create a VegFood class that will implements the Food interface
and override its all methods.
File: VegFood.java
File: FoodDecorator.java
File: NonVegFood.java
File: ChineeseFood.java
File: DecoratorPatternCustomer.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class DecoratorPatternCustomer {
5. private static int choice;
6. public static void main(String args[]) throws NumberFormatExceptio
n, IOException {
7. do{
8. System.out.print("========= Food Menu ============ \
n");
9. System.out.print(" 1. Vegetarian Food. \n");
10. System.out.print(" 2. Non-Vegetarian Food.\n");
11. System.out.print(" 3. Chineese Food. \n");
12. System.out.print(" 4. Exit \n");
13. System.out.print("Enter your choice: ");
14. BufferedReader br=new BufferedReader(new InputStreamReader(Sy
stem.in));
15. choice=Integer.parseInt(br.readLine());
16. switch (choice) {
17. case 1:{
18. VegFood vf=new VegFood();
19. System.out.println(vf.prepareFood());
20. System.out.println( vf.foodPrice());
21. }
22. break;
23.
24. case 2:{
25. Food f1=new NonVegFood((Food) new VegFood());
26. System.out.println(f1.prepareFood());
27. System.out.println( f1.foodPrice());
28. }
29. break;
30. case 3:{
31. Food f2=new ChineeseFood((Food) new VegFood());
32. System.out.println(f2.prepareFood());
33. System.out.println( f2.foodPrice());
34. }
35. break;
36.
37. default:{
38. System.out.println("Other than these no food available");
39. }
40. return;
41. }//end of switch
42.
43. }while(choice!=4);
44. }
45. }
Facade Pattern
1. Facade Design Pattern
2. Advantage of Facade DP
3. Usage of Facade DP
4. UML of Facade DP
5. Example of Facade DP
A Facade Pattern says that just "just provide a unified and simplified
interface to a set of interfaces in a subsystem, therefore it hides
the complexities of the subsystem from the client".
It is used:
ADVERTISEMENT BY ADRECOVER
File: MobileShop.java
File: Iphone.java
File: Samsung.java
File: Blackberry.java
File: ShopKeeper.java
File: FacadePatternClient.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4.
5. public class FacadePatternClient {
6. private static int choice;
7. public static void main(String args[]) throws NumberFormatEx
ception, IOException{
8. do{
9. System.out.print("========= Mobile Shop ========
==== \n");
10. System.out.print(" 1. IPHONE. \n");
11. System.out.print(" 2. SAMSUNG. \n");
12. System.out.print(" 3. BLACKBERRY. \n");
13. System.out.print(" 4. Exit. \n");
14. System.out.print("Enter your choice: ");
15.
16. BufferedReader br=new BufferedReader(new InputStreamReader(
System.in));
17. choice=Integer.parseInt(br.readLine());
18. ShopKeeper sk=new ShopKeeper();
19.
20. switch (choice) {
21. case 1:
22. {
23. sk.iphoneSale();
24. }
25. break;
26. case 2:
27. {
28. sk.samsungSale();
29. }
30. break;
31. case 3:
32. {
33. sk.blackberrySale();
34. }
35. break;
36. default:
37. {
38. System.out.println("Nothing You purchased");
39. }
40. return;
41. }
42.
43. }while(choice!=4);
44. }
45. }
A Flyweight Pattern says that just "to reuse already existing similar
kind of objects by storing them and create new object when no
matching object is found".
Proxy Pattern
1. Proxy Design Pattern
2. Advantage of Proxy DP
3. Usage of Proxy DP
4. UML of Proxy DP
5. Example of Proxy DP
So, we can perform many operations like hiding the information of original
object, on demand loading etc.
Proxy pattern is also known as Surrogate or Placeholder.
RMI API uses proxy design pattern. Stub and Skeleton are two proxy objects used
in RMI.
Advantage of Proxy Pattern
o It provides the protection to the original object from the outside world.
It is used:
ADVERTISEMENT BY ADRECOVER
File: RealInternetAccess.java
File: ProxyInternetAccess.java
File: ProxyPatternClient.java
That means the implementation and the client should be loosely coupled
in order to avoid hard coding and dependencies.
In other words, we can say that normally each receiver contains reference
of another receiver. If one object cannot handle the request then it passes
the same to the next receiver and so on.
It is used:
o When more than one object can handle a request and the handler is
unknown.
o When the group of objects that can handle the request must be specified
in dynamic way.
ADVERTISEMENT BY ADRECOVER
File: ConsoleBasedLogger.java
File: DebugBasedLogger.java
File: ErrorBasedLogger.java
File: ChainofResponsibilityClient.java
1. bilityClient
2. CONSOLE LOGGER INFO: Enter the sequence of values
3. CONSOLE LOGGER INFO: An error is occured now
4. ERROR LOGGER INFO: An error is occured now
5. CONSOLE LOGGER INFO: This was the error now debugging is comp
eled
6. ERROR LOGGER INFO: This was the error now debugging is compele
d
7. DEBUG LOGGER INFO: This was the error now debugging is compele
d
Command Pattern
1. Command Design Pattern
2. Advantage of Command DP
3. Usage of Command DP
4. UML of Command DP
5. Example of Command DP
It is used:
ADVERTISEMENT BY ADRECOVER
File: Document.java
File: ActionOpen.java
File: AdapterPatternDemo.java
File: ActionSave.java
File: AdapterPatternDemo.java
Interpreter Pattern
1. Interpreter Design Pattern
2. Advantage of Interpreter DP
3. Usage of Interpreter DP
4. UML of Interpreter DP
5. Example of Interpreter DP
Basically the Interpreter pattern has limited area where it can be applied.
We can discuss the Interpreter pattern only in terms of formal grammars
but in this area there are better solutions that is why it is not frequently
used.
This pattern can applied for parsing the expressions defined in simple
grammars and sometimes in simple rule engines.
It is used:
ADVERTISEMENT BY ADRECOVER
File: InfixToPostfixPattern.java
1. import java.util.Stack;
2. public class InfixToPostfixPattern implements Pattern{
3. @Override
4. public String conversion(String exp) {
5. int priority = 0;// for the priority of operators.
6. String postfix = "";
7. Stack<Character> s1 = new Stack<Character>();
8. for (int i = 0; i < exp.length(); i++)
9. {
10. char ch = exp.charAt(i);
11. if (ch == '+' || ch == '-' || ch == '*' || ch == '/'||
ch=='%')
12. {
13. // check the precedence
14. if (s1.size() <= 0)
15. s1.push(ch);
16. }
17. else
18. {
19. Character chTop = (Character) s1.peek();
20. if (chTop == '*' || chTop == '/')
21. priority = 1;
22. else
23. priority = 0;
24. if (priority == 1)
25. {
26. if (ch == '*' || ch == '/'||ch=='%')
27. {
28. postfix += s1.pop();
29. i--;
30. }
31. else
32. { // Same
33. postfix += s1.pop();
34. i--;
35. }
36. }
37. else
38. {
39. if (ch == '+' || ch == '-')
40. {
41. postfix += s1.pop();
42. s1.push(ch);
43. }
44. else
45. s1.push(ch);
46. }
47. }
48. }
49. else
50. {
51. postfix += ch;
52. }
53. }
54. int len = s1.size();
55. for (int j = 0; j < len; j++)
56. postfix += s1.pop();
57. return postfix;
58.
59. }
60.}// End of the InfixToPostfixPattern class.
Step 3
File: InterpreterPatternClient.java
OP
1. Infix: a+b*c
2. Postfix: abc*+
Iterator Pattern
1. Iterator Design Pattern
2. Advantage of Iterator DP
3. Usage of Iterator DP
4. UML of Iterator DP
5. Example of Iterator DP
It is used:
ADVERTISEMENT BY ADRECOVER
File: CollectionofNames.java
File: IteratorPatternDemo.java
1. public class IteratorPatternDemo {
2. public static void main(String[] args) {
3. CollectionofNames cmpnyRepository = new CollectionofName
s();
4.
5. for(Iterator iter = cmpnyRepository.getIterator(); iter.hasNext
();){
6. String name = (String)iter.next();
7. System.out.println("Name : " + name);
8. }
9. }
10.}
Output
1. Name : Ashwani Rajput
2. Name : Soono Jaiswal
3. Name : Rishi Kumar
4. Name : Rahul Mehta
5. Name : Hemant Mishra
Mediator Pattern
A Mediator Pattern says that "to define an object that encapsulates how a
set of objects interact".
Usage:
ADVERTISEMENT BY ADRECOVER
Participants:
o ApnaChatroom :- defines the interface for interacting with participants.
o ApnaChatroomImpl :- implements the operations defined by the
Chatroom interface. The operations are managing the interactions
between the objects: when one participant sends a message, the message
is sent to the other participants.
o Participant :- defines an interface for the users involved in chatting.
o User1, User2, ...UserN :- implements Participant interface; the
participant can be a number of users involved in chatting. But each
Participant will keep only a reference to the ApnaChatRoom.
ADVERTISEMENT BY ADRECOVER
1. //This is an interface.
2. public interface ApnaChatRoom {
3.
4. public void showMsg(String msg, Participant p);
5.
6. }// End of the ApnaChatRoom interface.
Step 2:
1. //This is a class.
2. import java.text.DateFormat;
3. import java.text.SimpleDateFormat;
4. import java.util.Date;
5.
6. public class ApnaChatRoomImpl implements ApnaChatRoom{
7. //get current date time
8. DateFormat dateFormat = new SimpleDateFormat("E dd-MM-yyyy hh:m
m a");
9. Date date = new Date();
10. @Override
11. public void showMsg(String msg, Participant p) {
12.
13. System.out.println(p.getName()+"'gets message:
"+msg);
14. System.out.println("\t\t\t\t"+"["+dateFormat.format(date).toString()
+"]");
15. }
16.}// End of the ApnaChatRoomImpl class.
Step 3:
Step 4:
Create a User1 class that will extend Participant abstract class and will use
the ApnaChatRoom interface.
1. //This is a class.
2.
3. public class User1 extends Participant {
4.
5. private String name;
6. private ApnaChatRoom chat;
7.
8. @Override
9. public void sendMsg(String msg) {
10. chat.showMsg(msg,this);
11.
12. }
13.
14. @Override
15. public void setname(String name) {
16. this.name=name;
17. }
18.
19. @Override
20. public String getName() {
21. return name;
22. }
23.
24. public User1(ApnaChatRoom chat){
25. this.chat=chat;
26. }
27.
28.}// End of the User1 class.
Step 5:
Create a User2 class that will extend Participant abstract class and will use
the ApnaChatRoom interface.
1. //This is a class.
2.
3. public class User2 extends Participant {
4.
5. private String name;
6. private ApnaChatRoom chat;
7.
8. @Override
9. public void sendMsg(String msg) {
10. this.chat.showMsg(msg,this);
11.
12. }
13.
14. @Override
15. public void setname(String name) {
16. this.name=name;
17. }
18.
19. @Override
20. public String getName() {
21. return name;
22. }
23.
24. public User2(ApnaChatRoom chat){
25. this.chat=chat;
26. }
27.
28.
29.
30.}
31. // End of the User2 class.
Step 6:
1. //This is a class.
2.
3. public class MediatorPatternDemo {
4.
5. public static void main(String args[])
6. {
7.
8. ApnaChatRoom chat = new ApnaChatRoomImpl();
9.
10. User1 u1=new User1(chat);
11. u1.setname("Ashwani Rajput");
12. u1.sendMsg("Hi Ashwani! how are you?");
13.
14.
15. User2 u2=new User2(chat);
16. u2.setname("Soono Jaiswal");
17. u2.sendMsg("I am Fine ! You tell?");
18. }
19.
20.}// End of the MediatorPatternDemo class.
Output:
Memento Pattern
A Memento Pattern says that "to restore the state of an object to its
previous state". But it must do this without violating Encapsulation. Such
case is useful in case of error or failure.
Benefits:
o It preserves encapsulation boundaries.
o It simplifies the originator.
Usage:
ADVERTISEMENT BY ADRECOVER
Memento:
o Stores internal state of the originator object. The state can include any
number of state variables.
o The Memento must have two interfaces, an interface to the caretaker. This
interface must not allow any operations or any access to internal state
stored by the memento and thus maintains the encapsulation. The other
interface is Originator and it allows the Originator to access any state
variables necessary to the originator to restore the previous state.
Originator:
Caretaker:
ADVERTISEMENT BY ADRECOVER
Create an Originator class that will use Memento object to restore its
previous state.
1. //This is a class.
2.
3. public class Originator {
4.
5. private String state;
6.
7. public void setState(String state){
8. this.state = state;
9. }
10.
11. public String getState(){
12. return state;
13. }
14.
15. public Memento saveStateToMemento(){
16. return new Memento(state);
17. }
18.
19. public void getStateFromMemento(Memento Memento){
Step 2:
Create a Memento class that will Store internal state of the Originator
object.
1. //This is a class.
2.
3. public class Memento {
4.
5. private String state;
6.
7. public Memento(String state) {
8. this.state=state;
9. }
10. public String getState() {
11. return state;
12. }
13.
14.}// End of the Memento class.
Step 3:
Create a Caretaker class that will responsible for keeping the Memento.
1. //This is a class.
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6.
7. public class Caretaker {
8.
9. private List<Memento> mementoList = new ArrayList<Mement
o>();
10.
11. public void add(Memento state){
12. mementoList.add(state);
13. }
14.
15. public Memento get(int index){
16. return mementoList.get(index);
17. }
18.
19. }// End of the Caretaker class.
Step 4:
1. //This is a class.
2.
3.
4. public class MementoPatternDemo {
5.
6. public static void main(String[] args) {
7.
8. Originator originator = new Originator();
9.
10. Caretaker careTaker = new Caretaker();
11.
12. originator.setState("State #1");
13. careTaker.add(originator.saveStateToMemento());
14. originator.setState("State #2");
15. careTaker.add(originator.saveStateToMemento());
16. originator.setState("State #3");
17. careTaker.add(originator.saveStateToMemento());
18. originator.setState("State #4");
19.
20. System.out.println("Current State: " + originator.getState());
21. originator.getStateFromMemento(careTaker.get(0));
22. System.out.println("First saved State: " + originator.getState());
23. originator.getStateFromMemento(careTaker.get(1));
24. System.out.println("Second saved State: " + originator.getState());
25. originator.getStateFromMemento(careTaker.get(2));
26. System.out.println("Third saved State: " + originator.getState());
27. }
28.
29. }
30.// End of the MementoPatternDemo class.
Output:
Observer Pattern
An Observer Pattern says that "just define a one-to-one dependency so
that when one object changes state, all its dependents are notified and
updated automatically".
Benefits:
Usage:
ADVERTISEMENT BY ADRECOVER
1. //This is a class.
2.
3. import java.util.Observable;
4. import java.util.Observer;
5.
6. public class ResponseHandler1 implements Observer {
7. private String resp;
8. public void update(Observable obj, Object arg) {
9. if (arg instanceof String) {
10. resp = (String) arg;
11. System.out.println("\nReceived Response: " + resp );
12. }
13. }
14.}// End of the ResponseHandler1 interface.
Step 2:
1. //This is a class.
2.
3. import java.util.Observable;
4. import java.util.Observer;
5.
6. public class ResponseHandler2 implements Observer {
7. private String resp;
8. public void update(Observable obj, Object arg) {
9. if (arg instanceof String) {
10. resp = (String) arg;
11. System.out.println("\nReceived Response: " + resp );
12. }
13. }
14.}// End of the ResponseHandler2 interface.
Step 3:
1. //This is a class.
2.
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.io.InputStreamReader;
6. import java.util.Observable;
7.
8. public class EventSource extends Observable implements Runnable {
9. @Override
10. public void run() {
11. try {
12. final InputStreamReader isr = new InputStreamReader(System.in)
;
13. final BufferedReader br = new BufferedReader(isr);
14. while (true) {
15. String response = br.readLine();
16. setChanged();
17. notifyObservers(response);
18. }
19. }
20. catch (IOException e) {
21. e.printStackTrace();
22. }
23. }
24.}// End of the Eventsource class.
Output:
State Pattern
A State Pattern says that "the class behavior changes based on its state".
In State Pattern, we create objects which represent various states and a
context object whose behavior varies as its state object changes.
Usage:
o When the behavior of object depends on its state and it must be able to
change its behavior at runtime according to the new state.
o It is used when the operations have large, multipart conditional
statements that depend on the state of an object.
ADVERTISEMENT BY ADRECOVER
ADVERTISEMENT BY ADRECOVER
1. //This is an interface.
2.
3. public interface Connection {
4.
5. public void open();
6. public void close();
7. public void log();
8. public void update();
9. }// End of the Connection interface.
Step 2:
1. //This is a class.
2. public class Accounting implements Connection {
3.
4. @Override
5. public void open() {
6. System.out.println("open database for accounting");
7. }
8. @Override
9. public void close() {
10. System.out.println("close the database");
11. }
12.
13. @Override
14. public void log() {
15. System.out.println("log activities");
16. }
17.
18. @Override
19. public void update() {
20. System.out.println("Accounting has been updated");
21. }
22.}// End of the Accounting class.
Step 3:
1. //This is a class.
2. public class Sales implements Connection {
3.
4. @Override
5. public void open() {
6. System.out.println("open database for sales");
7. }
8. @Override
9. public void close() {
10. System.out.println("close the database");
11. }
12.
13. @Override
14. public void log() {
15. System.out.println("log activities");
16. }
17.
18. @Override
19. public void update() {
20. System.out.println("Sales has been updated");
21. }
22.
23. }// End of the Sales class.
Step 4:
1. //This is a class.
2.
3. public class Sales implements Connection {
4.
5. @Override
6. public void open() {
7. System.out.println("open database for sales");
8. }
9. @Override
10. public void close() {
11. System.out.println("close the database");
12. }
13. @Override
14. public void log() {
15. System.out.println("log activities");
16. }
17. @Override
18. public void update() {
19. System.out.println("Sales has been updated");
20. }
21. }// End of the Sales class.
Step 5:
1. //This is a class.
2.
3.
4. public class Management implements Connection {
5.
6. @Override
7. public void open() {
8. System.out.println("open database for Management");
9. }
10. @Override
11. public void close() {
12. System.out.println("close the database");
13. }
14.
15. @Override
16. public void log() {
17. System.out.println("log activities");
18. }
19.
20. @Override
21. public void update() {
22. System.out.println("Management has been updated");
23. }
24.
25. }
26. // End of the Management class.
Step 6:
Create a Controller class that will use the Connection interface for
connecting with different types of connection.
1. //This is a class.
2.
3. public class Controller {
4.
5. public static Accounting acct;
6. public static Sales sales;
7. public static Management management;
8.
9. private static Connection con;
10.
11. Controller() {
12. acct = new Accounting();
13. sales = new Sales();
14. management = new Management();
15. }
16.
17. public void setAccountingConnection() {
18. con = acct;
19. }
20. public void setSalesConnection() {
21. con = sales;
22. }
23. public void setManagementConnection() {
24. con = management;
25. }
26. public void open() {
27. con .open();
28. }
29. public void close() {
30. con .close();
31. }
32. public void log() {
33. con .log();
34. }
35. public void update() {
36. con .update();
37. }
38.
39.
40.}// End of the Controller class.
Step 7:
1. //This is a class.
2.
3.
4. public class StatePatternDemo {
5.
6. Controller controller;
7. StatePatternDemo(String con) {
8. controller = new Controller();
9. //the following trigger should be made by the user
10. if(con.equalsIgnoreCase("management"))
11. controller.setManagementConnection();
12. if(con.equalsIgnoreCase("sales"))
13. controller.setSalesConnection();
14. if(con.equalsIgnoreCase("accounting"))
15. controller.setAccountingConnection();
16. controller.open();
17. controller.log();
18. controller.close();
19. controller.update();
20. }
21.
22.
23. public static void main(String args[]) {
24.
25. new StatePatternDemo(args[0]);
26.
27. }
28.
29. }// End of the StatePatternDemo class.
Output:
Strategy Pattern
A Strategy Pattern says that "defines a family of functionality, encapsulate
each one, and make them interchangeable".
Benefits:
Usage:
o When the multiple classes differ only in their behaviors.e.g. Servlet API.
o It is used when you need different variations of an algorithm.
ADVERTISEMENT BY ADRECOVER
ADVERTISEMENT BY ADRECOVER
1. //This is an interface.
2.
3. public interface Strategy {
4.
5. public float calculation(float a, float b);
6.
7. }// End of the Strategy interface.
Step 2:
1. //This is a class.
2. public class Addition implements Strategy{
3.
4. @Override
5. public float calculation(float a, float b) {
6. return a+b;
7. }
8.
9. }// End of the Addition class.
Step 3:
1. //This is a class.
2. public class Subtraction implements Strategy{
3.
4. @Override
5. public float calculation(float a, float b) {
6. return a-b;
7. }
8.
9. }// End of the Subtraction class.
Step 4:
1. //This is a class.
2.
3. public class Multiplication implements Strategy{
4.
5. @Override
6. public float calculation(float a, float b){
7. return a*b;
8. }
9. }// End of the Multiplication class.
Step 5:
Create a Context class that will ask from Startegy interface to execute the
type of strategy.
1. //This is a class.
2.
3.
4. public class Context {
5.
6. private Strategy strategy;
7.
8. public Context(Strategy strategy){
9. this.strategy = strategy;
10. }
11.
12. public float executeStrategy(float num1, float num2){
13. return strategy.calculation(num1, num2);
14. }
15. }// End of the Context class.
Step 6:
1. //This is a class.
2. import java.io.BufferedReader;
3. import java.io.IOException;
4. import java.io.InputStreamReader;
5.
6. public class StrategyPatternDemo {
7.
8. public static void main(String[] args) throws NumberFormatExceptio
n, IOException {
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader(S
ystem.in));
11. System.out.print("Enter the first value: ");
12. float value1=Float.parseFloat(br.readLine());
13. System.out.print("Enter the second value: ");
14. float value2=Float.parseFloat(br.readLine());
15. Context context = new Context(new Addition());
16. System.out.println("Addition = " + context.executeStrategy(value1,
value2));
17.
18. context = new Context(new Subtraction());
19. System.out.println("Subtraction = " + context.executeS
trategy(value1, value2));
20.
21. context = new Context(new Multiplication());
22. System.out.println("Multiplication = " + context.executeStrategy(val
ue1, value2));
23. }
24.
25. }// End of the StrategyPatternDemo class.
Output:
Template Pattern
A Template Pattern says that "just define the skeleton of a function in an
operation, deferring some steps to its subclasses".
Benefits:
o It is very common technique for reusing the code.This is only the main
benefit of it.
Usage:
ADVERTISEMENT BY ADRECOVER
ADVERTISEMENT BY ADRECOVER
Step 2:
Create a Chess class that will extend Game abstract class for giving the
definition to its method.
1. //This is a class.
2.
3. public class Chess extends Game {
4. @Override
5. void initialize() {
6. System.out.println("Chess Game Initialized! Start playing.");
7. }
8. @Override
9. void start() {
10. System.out.println("Game Started. Welcome to in the chess game!")
;
11. }
12. @Override
13. void end() {
14. System.out.println("Game Finished!");
15. }
16.}// End of the Chess class.
Step 3:
Create a Soccer class that will extend Game abstract class for giving the
definition to its method.
1. //This is a class.
2.
3.
4. public class Soccer extends Game {
5.
6. @Override
7. void initialize() {
8. System.out.println("Soccer Game Initialized! Start playing.");
9. }
10.
11. @Override
12. void start() {
13. System.out.println("Game Started. Welcome to in the S
occer game!");
14. }
15.
16. @Override
17. void end() {
18. System.out.println("Game Finished!");
19. }
20.}// End of the Soccer class.
Step 4:
1. //This is a class.
2. public class TemplatePatternDemo {
3.
4. public static void main(String[] args) throws InstantiationException, Ille
galAccessException, ClassNotFoundException {
5.
6. Class c=Class.forName(args[0]);
7. Game game=(Game) c.newInstance();
8. game.play();
9. }
10.}// End of the Soccer class.
Output:
In J2EE , there are mainly three types of design patterns, which are further
divided into their sub-parts:
1. Presentation Layer Design Pattern
Presentation Layer
Usage:
ADVERTISEMENT BY ADRECOVER
ADVERTISEMENT BY ADRECOVER
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="US-ASCII">
5. <title>Login Page</title>
6. </head>
7. <body>
8.
9. <form action="LoginServlet" method="post">
10.
11. Username: <input type="text" name="username">
12.<br><br>
13. Password: <input type="password" name="password">
14.<br><br>
15. <input type="submit" value="Login">
16.
17. </form>
18.</body>
Step 2
1. package sessions;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5.
6. import javax.servlet.RequestDispatcher;
7. import javax.servlet.ServletException;
8. import javax.servlet.annotation.WebServlet;
9. import javax.servlet.http.Cookie;
10.import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12.import javax.servlet.http.HttpServletResponse;
13. import javax.servlet.http.HttpSession;
14.**
15. * Servlet implementation class LoginServlet
16. */
17. @WebServlet("/LoginServlet")
18.public class LoginServlet extends HttpServlet {
19. private static final long serialVersionUID = 1L;
20. private final String user = "admin";
21. private final String password = "admin@1234";
22.
23. public LoginServlet() {
24. super();
25. }
26.protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
27.
28. // get request parameters for username and passwd
29. String username = request.getParameter("username");
30. String passwd = request.getParameter("password");
31.
32. if(user.equals(username) && password.equals(passwd)){
33. HttpSession session = request.getSession();
34. session.setAttribute("user", "ashwani");
35.
36. //setting session to expire in 1 hour
37. session.setMaxInactiveInterval(60*60);
38.
39. Cookie userName = new Cookie("user", user);
40. userName.setMaxAge(60*60);
41. response.addCookie(userName);
42. response.sendRedirect("LoginSuccess.jsp");
43. }else{
44. RequestDispatcher rd = getServletContext().getRequestDispatcher
("/Login.html");
45. PrintWriter out= response.getWriter();
46. out.println("<font color=red>Either user name or password is wro
ng.</font>");
47. rd.include(request, response);
48. }
49. }
50.}//End of the LoginServlet class.
Step 3
Step 5
Step 6
1. package filters;
2.
3. import java.io.IOException;
4. import javax.servlet.Filter;
5. import javax.servlet.FilterChain;
6. import javax.servlet.FilterConfig;
7. import javax.servlet.ServletContext;
8. import javax.servlet.ServletException;
9. import javax.servlet.ServletRequest;
10.import javax.servlet.ServletResponse;
11. import javax.servlet.annotation.WebFilter;
12.import javax.servlet.http.HttpServletRequest;
13. import javax.servlet.http.HttpServletResponse;
14.import javax.servlet.http.HttpSession;
15.
16./**
17. * Servlet Filter implementation class AuthenticationFilter
18. */
19. @WebFilter("/AuthenticationFilter")
20.public class AuthenticationFilter implements Filter {
21.
22. private ServletContext context;
23.
24. public void init(FilterConfig fConfig) throws ServletException {
25. this.context = fConfig.getServletContext();
26. this.context.log("AuthenticationFilter initialized");
27. }
28.
29. public void doFilter(ServletRequest request, ServletRespon
se response, FilterChain chain) throws IOException, ServletExceptio
n{
30.
31. HttpServletRequest req = (HttpServletRequest) request;
32. HttpServletResponse res = (HttpServletResponse) response;
33.
34. String uri = req.getRequestURI();
35. this.context.log("Requested Resource::"+uri);
36.
37. HttpSession session = req.getSession(false);
38.
39. if(session == null && !(uri.endsWith("html") || uri.endsW
ith("LoginServlet"))){
40. this.context.log("Unauthorized access request");
41. res.sendRedirect("Login.html");
42. }else{
43. // pass the request along the filter chain
44. chain.doFilter(request, response);
45. }
46. }
47. public void destroy() {
48. //close any resources here
49. }
50.}//End of the AuthenticationFilter class
Step 7
1. package filters;
2. import java.io.IOException;
3. import java.util.Enumeration;
4. import javax.servlet.Filter;
5. import javax.servlet.FilterChain;
6. import javax.servlet.FilterConfig;
7. import javax.servlet.ServletContext;
8. import javax.servlet.ServletException;
9. import javax.servlet.ServletRequest;
10.import javax.servlet.ServletResponse;
11. import javax.servlet.annotation.WebFilter;
12.import javax.servlet.http.Cookie;
13. import javax.servlet.http.HttpServletRequest;
14.@WebFilter("/RequestLoggingFilter")
15. public class RequestLoggingFilter implements Filter {
16.private ServletContext context;
17. public void init(FilterConfig fConfig) throws ServletExceptio
n{
18. this.context = fConfig.getServletContext();
19. this.context.log("RequestLoggingFilter initialized");
20. }
21. public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain) throws IOException, ServletException
{
22. HttpServletRequest req = (HttpServletRequest) request;
23. Enumeration<String> params = req.getParameterNames
();
24.while(params.hasMoreElements()){
25. String name = params.nextElement();
26. String value = request.getParameter(name);
27. this.context.log(req.getRemoteAddr() + "::Request Par
ams::{"+name+"="+value+"}");
28. }
29.
30. Cookie[] cookies = req.getCookies();
31. if(cookies != null){
32. for(Cookie cookie : cookies){
33. this.context.log(req.getRemoteAddr() + "::Cookie::
{"+cookie.getName()+","+cookie.getValue()+"}");
34. }
35. }
36. // pass the request along the filter chain
37. chain.doFilter(request, response);
38. }
39.
40. public void destroy() {
41. //we can close resources here
42. }
43. }// End of the RequestLoggingFilter class
Step 8
Output:
Front Controller Pattern
A Front Controller Pattern says that if you want to provide the centralized
request handling mechanism so that all the requests will be handled by a
single handler". This handler can do the authentication or authorization or
logging or tracking of request and then pass the requests to
corresponding handlers.
Usage:
o When you want to control the page flow and navigation.
o When you want to access and manage the data model.
o When you want to handle the business processing.
Benefits:
ADVERTISEMENT BY ADRECOVER
ADVERTISEMENT BY ADRECOVER
1. <html>
2. <head>
3. <title>
4. Login page
5. </title>
6. </head>
7. <body style="color:green;">
8. <h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
9. color:#00FF00;>
10.Login Page
11. </h1>
12.<form method="POST" action="FrontControllerServlet" onsubmit="return
checkForm(this);">
13. <p>Username: <input type="text" name="username"></
p>
14.<p>Password: <input type="password" name="pwd1"></p>
15. <p>Confirm Password: <input type="password" name="pwd
2"></p>
16.<p><input type="submit" value="Login"></p>
17. </form>
18.<script type="text/javascript">
19.
20. function checkForm(form)
21. {
22. if(form.username.value == "") {
23. alert("Error: Username cannot be blank!");
24. form.username.focus();
25. return false;
26. }
27. re = /^\w+$/;
28. if(!re.test(form.username.value)) {
29. alert("Error: Username must contain only letters, numbers
and underscores!");
30. form.username.focus();
31. return false;
32. }
33.
34. if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
35. if(form.pwd1.value.length < 6) {
36. alert("Error: Password must contain at least six characters!");
37. form.pwd1.focus();
38. return false;
39. }
40. if(form.pwd1.value == form.username.value) {
41. alert("Error: Password must be different from Username!"
);
42. form.pwd1.focus();
43. return false;
44. }
45. re = /[0-9]/;
46. if(!re.test(form.pwd1.value)) {
47. alert("Error: password must contain at least one number
(0-9)!");
48. form.pwd1.focus();
49. return false;
50. }
51. re = /[a-z]/;
52. if(!re.test(form.pwd1.value)) {
53. alert("Error: password must contain at least one lowercas
e letter (a-z)!");
54. form.pwd1.focus();
55. return false;
56. }
57. re = /[A-Z]/;
58. if(!re.test(form.pwd1.value)) {
59. alert("Error: password must contain at least one upperca
se letter (A-Z)!");
60. form.pwd1.focus();
61. return false;
62. }
63. } else {
64. alert("Error: Please check that you've entered and confirmed your pass
word!");
65. form.pwd1.focus();
66. return false;
67. }
68. return true;
69. }
70.
71. </script>
72.</body>
73. </html>
Step 2
1. package controller;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5.
6. import javax.servlet.RequestDispatcher;
7. import javax.servlet.ServletException;
8. import javax.servlet.annotation.WebServlet;
9. import javax.servlet.http.HttpServlet;
10.import javax.servlet.http.HttpServletRequest;
11. import javax.servlet.http.HttpServletResponse;
12.
13. /**
14. * Servlet implementation class FrontControllerServlet
15. */
16.@WebServlet("/FrontControllerServlet")
17. public class FrontControllerServlet extends HttpServlet {
18.
19. protected void doPost(HttpServletRequest request, HttpSe
rvletResponse response) throws ServletException, IOException {
20.
21. response.setContentType("text/html");
22. PrintWriter out = response.getWriter();
23.
24. String username=request.getParameter("username");
25. String password=request.getParameter("pwd2");
26.
27. if (password.equals("Ashwani1987")) {
28.
29. RequestDispatcher rd=request.getRequestDispatcher(
"/Success.jsp");
30. rd.forward(request, response);
31. } else {
32.
33. RequestDispatcher rd=request.getRequestDispatcher(
"/Error.jsp");
34. rd.forward(request, response);
35. }
36.
37. }
38.
39. }
Step 3
Step 4
Step 5
Output: