0% found this document useful (0 votes)
7 views189 pages

Design Patterns in Java

Uploaded by

Lovely Sankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views189 pages

Design Patterns in Java

Uploaded by

Lovely Sankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 189

Design Patterns in Java

A design patterns are well-proved solution for solving the specific


problem/task.

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.

But remember one-thing, design patterns are programming language


independent strategies for solving the common object-oriented design
problems. That means, a design pattern represents an idea, not a
particular implementation.

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.

To become a professional software developer, you must know at least


some popular solutions (i.e. design patterns) to the coding problems.

Advantage of design pattern:


1. They are reusable in multiple projects.
2. They provide the solutions that help to define the system
architecture.
3. They capture the software engineering experiences.
4. They provide transparency to the design of an application.
5. They are well-proved and testified solutions since they have been
built upon the knowledge and experience of expert software
developers.
6. Design patterns don?t guarantee an absolute solution to a problem.
They provide clarity to the system architecture and the possibility of
building a better system.

When should we use the design patterns?


We must use the design patterns during the analysis and
requirement phase of SDLC(Software Development Life Cycle).

Design patterns ease the analysis and requirement phase of SDLC by


providing information based on prior hands-on experiences.

Categorization of design patterns:


Basically, design patterns are categorized into two parts:

1. Core Java (or JSE) Design Patterns.


2. JEE Design Patterns.

Core Java Design Patterns


In core java, there are mainly three types of design patterns, which are
further divided into their sub-parts:

1.Creational Design Pattern


1. Factory Pattern
2. Abstract Factory Pattern
3. Singleton Pattern
4. Prototype Pattern
5. Builder Pattern.
ADVERTISEMENT BY ADRECOVER

2. Structural Design Pattern


1. Adapter Pattern
2. Bridge Pattern
3. Composite Pattern
4. Decorator Pattern
5. Facade Pattern
6. Flyweight Pattern
7. Proxy Pattern

3. Behavioral Design Pattern


1. Chain Of Responsibility Pattern
2. Command Pattern
3. Interpreter Pattern
4. Iterator Pattern
5. Mediator Pattern
6. Memento Pattern
7. Observer Pattern
8. State Pattern
9. Strategy Pattern
10. Template Pattern
11. Visitor Pattern

Creational design patterns


Creational design patterns are concerned with the way of creating
objects. These design patterns are used when a decision must be made
at the time of instantiation of a class (i.e. creating an object of a class).

But everyone knows an object is created by using new keyword in java.


For example:

1. StudentRecord s1=new StudentRecord();

Hard-Coded code is not the good programming approach. Here, we are


creating the instance by using the new keyword. Sometimes, the nature of
the object must be changed according to the nature of the program. In
such cases, we must get the help of creational design patterns to provide
more general and flexible approach.

Types of creational design patterns


There are following 6 types of creational design patterns.
1. Factory Method Pattern
2. Abstract Factory Pattern
3. Singleton Pattern
4. Prototype Pattern
5. Builder Pattern
6. Object Pool Pattern

Factory Method Pattern


A Factory Pattern or Factory Method Pattern says that just define an
interface or abstract class for creating an object but let the
subclasses decide which class to instantiate. In other words,
subclasses are responsible to create the instance of the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern


o Factory Method Pattern allows the sub-classes to choose the type of
objects to create.
o It promotes the loose-coupling by eliminating the need to bind
application-specific classes into the code. That means the code interacts
solely with the resultant interface or abstract class, so that it will work with
any classes that implement that interface or that extends that abstract
class.

Usage of Factory Design Pattern


o When a class doesn't know what sub-classes will be required to create
o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.

ADVERTISEMENT BY ADRECOVER

UML for Factory Method Pattern


o We are going to create a Plan abstract class and concrete classes that
extends the Plan abstract class. A factory class GetPlanFactory is defined
as a next step.
o GenerateBill class will use GetPlanFactory to get a Plan object. It will pass
information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to
GetPalnFactory to get the type of object it needs.

Calculate Electricity Bill : A Real World Example of Factory


Method
Step 1: Create a Plan abstract class.

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 DomesticPlan extends Plan{


2. //@override
3. public void getRate(){
4. rate=3.50;
5. }
6. }//end of DomesticPlan class.
1. class CommercialPlan extends Plan{
2. //@override
3. public void getRate(){
4. rate=7.50;
5. }
6. /end of CommercialPlan class.
1. class InstitutionalPlan extends Plan{
2. //@override
3. public void getRate(){
4. rate=5.50;
5. }
6. /end of InstitutionalPlan class.

Step 3: Create a GetPlanFactory to generate object of concrete classes


based on given information..

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.

Step 4: Generate Bill by using the GetPlanFactory to get the object of


concrete classes by passing an information such as type of plan
DOMESTICPLAN or COMMERCIALPLAN or INSTITUTIONALPLAN.

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.

download this Electricity bill Example


Output

Abstract Factory Pattern


Abstract Factory Pattern says that just define an interface or abstract
class for creating families of related (or dependent) objects but
without specifying their concrete sub-classes.That means Abstract
Factory lets a class returns a factory of classes. So, this is the reason that
Abstract Factory Pattern is one level higher than the Factory Pattern.

An Abstract Factory Pattern is also known as Kit.

Advantage of Abstract Factory Pattern


o Abstract Factory Pattern isolates the client code from concrete
(implementation) classes.
o It eases the exchanging of object families.
o It promotes consistency among objects.

Usage of Abstract Factory Pattern


o When the system needs to be independent of how its object are created,
composed, and represented.
o When the family of related objects has to be used together, then this
constraint needs to be enforced.
o When you want to provide a library of objects that does not show
implementations and only reveals interfaces.
o When the system needs to be configured with one of a multiple family of
objects.

ADVERTISEMENT BY ADRECOVER

UML for Abstract Factory Pattern

o We are going to create a Bank interface and a Loan abstract class as


well as their sub-classes.
o Then we will create AbstractFactory class as next step.
o Then after we will create concrete
classes, BankFactory, and LoanFactory that will
extends AbstractFactory class
o After that, AbstractFactoryPatternExample class uses
the FactoryCreator to get an object of AbstractFactory class.
o See the diagram carefully which is given below:
Example of Abstract Factory Pattern
Here, we are calculating the loan payment for different banks like HDFC,
ICICI, SBI etc.

Step 1: Create a Bank interface

1. import java.io.*;
2. interface Bank{
3. String getBankName();
4. }

Step 2: Create concrete classes that implement the Bank interface.

1. class HDFC implements Bank{


2. private final String BNAME;
3. public HDFC(){
4. BNAME="HDFC BANK";
5. }
6. public String getBankName() {
7. return BNAME;
8. }
9. }
1. class ICICI implements Bank{
2. private final String BNAME;
3. ICICI(){
4. BNAME="ICICI BANK";
5. }
6. public String getBankName() {
7. return BNAME;
8. }
9. }
1. class SBI implements Bank{
2. private final String BNAME;
3. public SBI(){
4. BNAME="SBI BANK";
5. }
6. public String getBankName(){
7. return BNAME;
8. }
9. }

Step 3: Create the Loan abstract class.

1. abstract class Loan{


2. protected double rate;
3. abstract void getInterestRate(double rate);
4. public void calculateLoanPayment(double loanamount, int years)
5. {
6. /*
7. to calculate the monthly loan payment i.e. EMI
8.
9. rate=annual interest rate/12*100;
10. n=number of monthly installments;
11. 1year=12 months.
12. so, n=years*12;
13.
14. */
15.
16. double EMI;
17. int n;
18.
19. n=years*12;
20. rate=rate/1200;
21. EMI=((rate*Math.pow((1+rate),n))/
((Math.pow((1+rate),n))-1))*loanamount;
22.
23. System.out.println("your monthly EMI is "+ EMI +" for the amo
unt"+loanamount+" you have borrowed");
24. }
25. }// end of the Loan abstract class.

Step 4: Create concrete classes that extend the Loan abstract class..

1. class HomeLoan extends Loan{


2. public void getInterestRate(double r){
3. rate=r;
4. }
5. }//End of the HomeLoan class.
1. class BussinessLoan extends Loan{
2. public void getInterestRate(double r){
3. rate=r;
4. }
5.
6. }//End of the BusssinessLoan class.
1. class EducationLoan extends Loan{
2. public void getInterestRate(double r){
3. rate=r;
4. }
5. }//End of the EducationLoan class.
Step 5: Create an abstract class (i.e AbstractFactory) to get the factories
for Bank and Loan Objects.

1. abstract class AbstractFactory{


2. public abstract Bank getBank(String bank);
3. public abstract Loan getLoan(String loan);
4. }

Step 6: Create the factory classes that inherit AbstractFactory class to


generate the object of concrete class based on given information.

1. class BankFactory extends AbstractFactory{


2. public Bank getBank(String bank){
3. if(bank == null){
4. return null;
5. }
6. if(bank.equalsIgnoreCase("HDFC")){
7. return new HDFC();
8. } else if(bank.equalsIgnoreCase("ICICI")){
9. return new ICICI();
10. } else if(bank.equalsIgnoreCase("SBI")){
11. return new SBI();
12. }
13. return null;
14. }
15. public Loan getLoan(String loan) {
16. return null;
17. }
18.}//End of the BankFactory class.
1. class LoanFactory extends AbstractFactory{
2. public Bank getBank(String bank){
3. return null;
4. }
5.
6. public Loan getLoan(String loan){
7. if(loan == null){
8. return null;
9. }
10. if(loan.equalsIgnoreCase("Home")){
11. return new HomeLoan();
12. } else if(loan.equalsIgnoreCase("Business")){
13. return new BussinessLoan();
14. } else if(loan.equalsIgnoreCase("Education")){
15. return new EducationLoan();
16. }
17. return null;
18. }
19.
20.}

Step 7: Create a FactoryCreator class to get the factories by passing an


information such as Bank or Loan.

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.

Step 8: Use the FactoryCreator to get AbstractFactory in order to get


factories of concrete classes by passing an information such as type.

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

download this Abstract Factory Pattern Example


Output

Singleton design pattern in Java


1. Singleton design pattern in Java
2. Advantage of Singleton Pattern
3. Usage of Singleton Pattern
4. Example of Singleton Pattern

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.

There are two forms of singleton design pattern

o Early Instantiation: creation of instance at load time.


o Lazy Instantiation: creation of instance when required.

Advantage of Singleton design pattern


o Saves memory because object is not created at each request. Only single
instance is reused again and again.

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.

Uml of Singleton design pattern

How to create Singleton design pattern?

To create the singleton class, we need to have static member of class,


private constructor and static factory method.

o Static member: It gets memory only once because of static, itcontains


the instance of the Singleton class.
o Private constructor: It will prevent to instantiate the Singleton class
from outside the class.
o Static factory method: This provides the global point of access to the
Singleton object and returns the instance to the caller.
Understanding early Instantiation of Singleton Pattern

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.

Let's see the example of singleton design pattern using early


instantiation.

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.}

Understanding lazy Instantiation of Singleton Pattern

In such case, we create the instance of the class in synchronized method


or synchronized block, so instance of the class is created when required.

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. }

Significance of Classloader in Singleton Pattern


If singleton class is loaded by two classloaders, two instance of singleton class
will be created, one for each classloader.

Significance of Serialization in Singleton Pattern


If singleton class is Serializable, you can serialize the singleton instance.
Once it is serialized, you can deserialize it but it will not return the
singleton object.

To resolve this issue, you need to override the readResolve()


method that enforces the singleton. It is called just after the object is
deserialized. It returns the singleton object.

1. public class A implements Serializable {


2. //your code of singleton
3. protected Object readResolve() {
4. return getA();
5. }
6.
7. }
Understanding Real Example of Singleton Pattern

o We are going to create a JDBCSingleton class. This JDBCSingleton class


contains its constructor as private and a private static instance jdbc of
itself.
o JDBCSingleton class provides a static method to get its static instance to
the outside world. Now, JDBCSingletonDemo class will use JDBCSingleton
class to get the JDBCSingleton object.
Assumption: you have created a table userdata that has three fields uid,
uname and upassword in mysql database. Database name is
ashwinirajput, username is root, password is ashwini.

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. }

download this Singleton Pattern Example


Output
Prototype Design Pattern
1. Prototype Design Pattern
2. Advantage of Prototype DP
3. Usage of Prototype DP
4. UML of Prototype DP
5. Example of Prototype DP

Prototype Pattern says that cloning of an existing object instead of


creating new one and can also be customized as per the
requirement.

This pattern should be followed, if the cost of creating a new object is


expensive and resource intensive.

Advantage of Prototype Pattern

The main advantages of prototype pattern are as follows:

o It reduces the need of sub-classing.


o It hides complexities of creating objects.
o The clients can get new objects without knowing which type of object it
will be.
o It lets you add or remove objects at runtime.

Usage of Prototype Pattern


o When the classes are instantiated at runtime.
o When the cost of creating an object is expensive or complicated.
o When you want to keep the number of classes in an application minimum.
o When the client application needs to be unaware of object creation and
representation.

ADVERTISEMENT BY ADRECOVER
UML for Prototype Pattern

o We are going to create an interface Prototype that contains a


method getClone() of Prototype type.
o Then, we create a concrete class EmployeeRecord which
implements Prototype interface that does the cloning of
EmployeeRecord object.
o PrototypeDemo class will uses this concrete class EmployeeRecord.

Example of Prototype Design Pattern


Let's see the example of prototype design pattern.
File: Prototype.java

1. interface Prototype {
2.
3. public Prototype getClone();
4.
5. }//End of Prototype interface.
File: EmployeeRecord.java

1. class EmployeeRecord implements Prototype{


2.
3. private int id;
4. private String name, designation;
5. private double salary;
6. private String address;
7.
8. public EmployeeRecord(){
9. System.out.println(" Employee Records of Oracle Corporati
on ");
10. System.out.println("---------------------------------------------");
11. System.out.println("Eid"+"\t"+"Ename"+"\
t"+"Edesignation"+"\t"+"Esalary"+"\t\t"+"Eaddress");
12.
13. }
14.
15. public EmployeeRecord(int id, String name, String designati
on, double salary, String address) {
16.
17. this();
18. this.id = id;
19. this.name = name;
20. this.designation = designation;
21. this.salary = salary;
22. this.address = address;
23. }
24.
25. public void showRecord(){
26.
27. System.out.println(id+"\t"+name+"\t"+designation+"\
t"+salary+"\t"+address);
28. }
29.
30. @Override
31. public Prototype getClone() {
32.
33. return new EmployeeRecord(id,name,designation,salary
,address);
34. }
35. }//End of EmployeeRecord class.
File: PrototypeDemo.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.

download this Prototype Pattern Example


Output

Builder Design Pattern


1. Builder Design Pattern
2. Advantage of Builder DP
3. Usage of Builder DP
4. UML of Builder DP
5. Example of Builder DP

Builder Pattern says that "construct a complex object from simple


objects using step-by-step approach"

It is mostly used when object can't be created in single step like in the de-
serialization of a complex object.

Advantage of Builder Design Pattern

The main advantages of Builder Pattern are as follows:

o It provides clear separation between the construction and representation


of an object.
o It provides better control over construction process.
o It supports to change the internal representation of objects.
UML for Builder Pattern Example

Example of Builder Design Pattern


To create simple example of builder design pattern, you need to follow 6
following steps.

1. Create Packing interface


2. Create 2 abstract classes CD and Company
3. Create 2 implementation classes of Company: Sony and Samsung
4. Create the CDType class
5. Create the CDBuilder class
6. Create the BuilderDemo class
1) Create Packing interface
File: Packing.java

1. public interface Packing {


2. public String pack();
3. public int price();
4. }
2) Create 2 abstract classes CD and Company

Create an abstract class CD which will implement Packing interface.

File: CD.java

1. public abstract class CD implements Packing{


2. public abstract String pack();
3. }
File: Company.java

1. public abstract class Company extends CD{


2. public abstract int price();
3. }
3) Create 2 implementation classes of Company: Sony and Samsung
File: Sony.java

1. public class Sony extends Company{


2. @Override
3. public int price(){
4. return 20;
5. }
6. @Override
7. public String pack(){
8. return "Sony CD";
9. }
10.}//End of the Sony class.
File: Samsung.java

1. public class Samsung extends Company {


2. @Override
3. public int price(){
4. return 15;
5. }
6. @Override
7. public String pack(){
8. return "Samsung CD";
9. }
10.}//End of the Samsung class.
4) Create the CDType class
File: CDType.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

1. public class CDBuilder {


2. public CDType buildSonyCD(){
3. CDType cds=new CDType();
4. cds.addItem(new Sony());
5. return cds;
6. }
7. public CDType buildSamsungCD(){
8. CDType cds=new CDType();
9. cds.addItem(new Samsung());
10. return cds;
11. }
12.}// End of the CDBuilder class.
6) Create the BuilderDemo class
File: BuilderDemo.java

1. public class BuilderDemo{


2. public static void main(String args[]){
3. CDBuilder cdBuilder=new CDBuilder();
4. CDType cdType1=cdBuilder.buildSonyCD();
5. cdType1.showItems();
6.
7. CDType cdType2=cdBuilder.buildSamsungCD();
8. cdType2.showItems();
9. }
10.}

download this builder pattern example

Output of the above example


1. CD name : Sony CD, Price : 20
2. CD name : Samsung CD, Price : 15

Another Real world example of Builder Pattern


UML for Builder Pattern:

We are considering a business case of pizza-hut where we can get


different varieties of pizza and cold-drink.

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.

Step 1:Create an interface Item that represents the Pizza and


Cold-drink.

File: Item.java

1. public interface Item


2. {
3. public String name();
4. public String size();
5. public float price();
6. }// End of the interface Item.

Step 2:Create an abstract class Pizza that will implement to the


interface Item.

File: Pizza.java

1. public abstract class Pizza implements Item{


2. @Override
3. public abstract float price();
4. }

Step 3:Create an abstract class ColdDrink that will implement to


the interface Item.

File: ColdDrink.java

1. public abstract class ColdDrink implements Item{


2. @Override
3. public abstract float price();

Step 4:Create an abstract class VegPizza that will extend to the


abstract class Pizza.

File: VegPizza.java

1. public abstract class VegPizza extends Pizza{


2. @Override
3. public abstract float price();
4. @Override
5. public abstract String name();
6. @Override
7. public abstract String size();
8. }// End of the abstract class VegPizza.

Step 5:Create an abstract class NonVegPizza that will extend to


the abstract class Pizza.

File: NonVegPizza.java

1. public abstract class NonVegPizza extends Pizza{


2. @Override
3. public abstract float price();
4. @Override
5. public abstract String name();
6. @Override
7. public abstract String size();
8. }// End of the abstract class NonVegPizza.

Step 6:Now, create concrete sub-classes SmallCheezePizza,


MediumCheezePizza, LargeCheezePizza, ExtraLargeCheezePizza
that will extend to the abstract class VegPizza.

File: SmallCheezePizza.java

1. public class SmallCheezePizza extends VegPizza{


2. @Override
3. public float price() {
4. return 170.0f;
5. }
6. @Override
7. public String name() {
8. return "Cheeze Pizza";
9. }
10. @Override
11. public String size() {
12. return "Small size";
13. }
14.}// End of the SmallCheezePizza class.
File: MediumCheezePizza.java

1. public class MediumCheezePizza extends VegPizza{


2. @Override
3. public float price() {
4. return 220.f;
5. }
6. @Override
7. public String name() {
8. return "Cheeze Pizza";
9. }
10. @Override
11. public String size() {
12. return "Medium Size";
13. }
14.}// End of the MediumCheezePizza class.
15. </textaera></div>
16.
17. <div id="filename">File: LargeCheezePizza.java</div>
18.<div class="codeblock"><textarea name="code" class="java">
19. public class LargeCheezePizza extends VegPizza{
20. @Override
21. public float price() {
22. return 260.0f;
23. }
24. @Override
25. public String name() {
26. return "Cheeze Pizza";
27. }
28. @Override
29. public String size() {
30. return "Large Size";
31. }
32.}// End of the LargeCheezePizza class.
File: ExtraLargeCheezePizza.java

1. public class ExtraLargeCheezePizza extends VegPizza{


2. @Override
3. public float price() {
4. return 300.f;
5. }
6. @Override
7. public String name() {
8. return "Cheeze Pizza";
9. }
10. @Override
11. public String size() {
12. return "Extra-Large Size";
13. }
14.}// End of the ExtraLargeCheezePizza class.
Step 7:Now, similarly create concrete sub-classes
SmallOnionPizza, MediumOnionPizza, LargeOnionPizza,
ExtraLargeOnionPizza that will extend to the abstract class
VegPizza.

File: SmallOnionPizza.java

1. public class SmallOnionPizza extends VegPizza {


2. @Override
3. public float price() {
4. return 120.0f;
5. }
6. @Override
7. public String name() {
8. return "Onion Pizza";
9. }
10. @Override
11. public String size() {
12. return "Small Size";
13. }
14.}// End of the SmallOnionPizza class.
File: MediumOnionPizza.java

1. public class MediumOnionPizza extends VegPizza {


2. @Override
3. public float price() {
4. return 150.0f;
5. }
6. @Override
7. public String name() {
8. return "Onion Pizza";
9. }
10. @Override
11. public String size() {
12. return "Medium Size";
13. }
14.}// End of the MediumOnionPizza class.
File: LargeOnionPizza.java

1. public class LargeOnionPizza extends VegPizza{


2. @Override
3. public float price() {
4. return 180.0f;
5. }
6. @Override
7. public String name() {
8. return "Onion Pizza";
9. }
10. @Override
11. public String size() {
12. return "Large size";
13. }
14.}// End of the LargeOnionPizza class.
File: ExtraLargeOnionPizza.java

1. public class ExtraLargeOnionPizza extends VegPizza {


2. @Override
3. public float price() {
4. return 200.0f;
5. }
6. @Override
7. public String name() {
8. return "Onion Pizza";
9. }
10. @Override
11. public String size() {
12. return "Extra-Large Size";
13. }
14.}// End of the ExtraLargeOnionPizza class

Step 8:Now, similarly create concrete sub-classes


SmallMasalaPizza, MediumMasalaPizza, LargeMasalaPizza,
ExtraLargeMasalaPizza that will extend to the abstract class
VegPizza.

File: SmallMasalaPizza.java

1. public class SmallMasalaPizza extends VegPizza{


2. @Override
3. public float price() {
4. return 100.0f;
5. }
6. @Override
7. public String name() {
8. return "Masala Pizza";
9. }
10. @Override
11. public String size() {
12. return "Samll Size";
13. }
14.}// End of the SmallMasalaPizza class
File: MediumMasalaPizza.java

1. public class MediumMasalaPizza extends VegPizza {


2.
3. @Override
4. public float price() {
5. return 120.0f;
6. }
7.
8. @Override
9. public String name() {
10.
11. return "Masala Pizza";
12.
13. }
14.
15. @Override
16. public String size() {
17. return "Medium Size";
18. }
File: LargeMasalaPizza.java

1. public class LargeMasalaPizza extends VegPizza{


2. @Override
3. public float price() {
4. return 150.0f;
5. }
6.
7. @Override
8. public String name() {
9.
10. return "Masala Pizza";
11.
12. }
13.
14. @Override
15. public String size() {
16. return "Large Size";
17. }
18.} //End of the LargeMasalaPizza class
File: ExtraLargeMasalaPizza.java

1. public class ExtraLargeMasalaPizza extends VegPizza {


2. @Override
3. public float price() {
4. return 180.0f;
5. }
6.
7. @Override
8. public String name() {
9.
10. return "Masala Pizza";
11.
12. }
13.
14. @Override
15. public String size() {
16. return "Extra-Large Size";
17. }
18.}// End of the ExtraLargeMasalaPizza class

Step 9:Now, create concrete sub-classes SmallNonVegPizza,


MediumNonVegPizza, LargeNonVegPizza, ExtraLargeNonVegPizza
that will extend to the abstract class NonVegPizza.

File: SmallNonVegPizza.java

1. public class SmallNonVegPizza extends NonVegPizza {


2.
3. @Override
4. public float price() {
5. return 180.0f;
6. }
7.
8. @Override
9. public String name() {
10. return "Non-Veg Pizza";
11. }
12.
13. @Override
14. public String size() {
15. return "Samll Size";
16. }
17.
18.}// End of the SmallNonVegPizza class
File: MediumNonVegPizza.java

1. public class MediumNonVegPizza extends NonVegPizza{


2.
3. @Override
4. public float price() {
5. return 200.0f;
6. }
7.
8. @Override
9. public String name() {
10. return "Non-Veg Pizza";
11. }
12.
13. @Override
14. public String size() {
15. return "Medium Size";
16. }
File: LargeNonVegPizza.java

1. public class LargeNonVegPizza extends NonVegPizza{


2.
3. @Override
4. public float price() {
5. return 220.0f;
6. }
7.
8. @Override
9. public String name() {
10. return "Non-Veg Pizza";
11. }
12.
13. @Override
14. public String size() {
15. return "Large Size";
16. }
17.
18.}// End of the LargeNonVegPizza class
File: ExtraLargeNonVegPizza.java

1. public class ExtraLargeNonVegPizza extends NonVegPizza {


2. @Override
3. public float price() {
4. return 250.0f;
5. }
6.
7. @Override
8. public String name() {
9. return "Non-Veg Pizza";
10. }
11.
12. @Override
13. public String size() {
14. return "Extra-Large Size";
15. }
16.
17. }
18.
19. // End of the ExtraLargeNonVegPizza class
Step 10:Now, create two abstract classes Pepsi and Coke that will
extend abstract class ColdDrink.

File: Pepsi.java

1. public abstract class Pepsi extends ColdDrink {


2.
3. @Override
4. public abstract String name();
5.
6. @Override
7. public abstract String size();
8.
9. @Override
10. public abstract float price();
11.
12.}// End of the Pepsi class
File: Coke.java

1. public abstract class Coke extends ColdDrink {


2.
3. @Override
4. public abstract String name();
5.
6. @Override
7. public abstract String size();
8.
9. @Override
10. public abstract float price();
11.
12.}// End of the Coke class
13.
14.</textaea></div>
15.
16.<p>Step 11:<b>Now, create concrete sub-classes SmallPepsi, MediumPe
psi, LargePepsi that will extend to the abstract class Pepsi.</b></p>
17. <div id="filename">File: SmallPepsi.java</div>
18.<div class="codeblock"><textarea name="code" class="java">
19. public class SmallPepsi extends Pepsi{
20.
21. @Override
22. public String name() {
23. return "300 ml Pepsi";
24. }
25.
26. @Override
27. public float price() {
28. return 25.0f;
29. }
30.
31. @Override
32. public String size() {
33. return "Small Size";
34. }
35. }// End of the SmallPepsi class
File: MediumPepsi.java

1. public class MediumPepsi extends Pepsi {


2.
3. @Override
4. public String name() {
5. return "500 ml Pepsi";
6. }
7.
8. @Override
9. public String size() {
10. return "Medium Size";
11. }
12.
13. @Override
14. public float price() {
15. return 35.0f;
16. }
17. }// End of the MediumPepsi class
File: LargePepsi.java

1. public class LargePepsi extends Pepsi{


2. @Override
3. public String name() {
4. return "750 ml Pepsi";
5. }
6.
7. @Override
8. public String size() {
9. return "Large Size";
10. }
11.
12. @Override
13. public float price() {
14. return 50.0f;
15. }
16.}// End of the LargePepsi class

Step 12:Now, create concrete sub-classes SmallCoke,


MediumCoke, LargeCoke that will extend to the abstract class
Coke.

File: SmallCoke.java

1. public class SmallCoke extends Coke{


2.
3. @Override
4. public String name() {
5. return "300 ml Coke";
6. }
7.
8. @Override
9. public String size() {
10.
11. return "Small Size";
12. }
13.
14. @Override
15. public float price() {
16.
17. return 25.0f;
18. }
19. }// End of the SmallCoke class
File: MediumCoke.java

1. public class MediumCoke extends Coke{


2.
3. @Override
4. public String name() {
5. return "500 ml Coke";
6. }
7.
8. @Override
9. public String size() {
10.
11. return "Medium Size";
12. }
13.
14. @Override
15. public float price() {
16.
17. return 35.0f;
18. }
19. }// End of the MediumCoke class
File: LargeCoke.java

1. public class LargeCoke extends Coke {


2. @Override
3. public String name() {
4. return "750 ml Coke";
5. }
6.
7. @Override
8. public String size() {
9.
10. return "Large Size";
11. }
12.
13. @Override
14. public float price() {
15.
16. return 50.0f;
17. }
18.}// End of the LargeCoke class
19.
20.</textrea></div>
21.
22.<p>Step 13:<b>Create an OrderedItems class that are having Item objec
ts defined above.</b></p>
23. <div id="filename">File: OrderedItems.java</div>
24.<div class="codeblock"><textarea name="code" class="java">
25. import java.util.ArrayList;
26.import java.util.List;
27. public class OrderedItems {
28.
29. List<Item> items=new ArrayList<Item>();
30.
31. public void addItems(Item item){
32.
33. items.add(item);
34. }
35. public float getCost(){
36.
37. float cost=0.0f;
38. for (Item item : items) {
39. cost+=item.price();
40. }
41. return cost;
42. }
43. public void showItems(){
44.
45. for (Item item : items) {
46. System.out.println("Item is:" +item.name());
47. System.out.println("Size is:" +item.size());
48. System.out.println("Price is: " +item.price());
49.
50. }
51. }
52.
53. }// End of the OrderedItems class

Step 14:Create an OrderBuilder class that will be responsible to


create the objects of OrderedItems class.

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("------------------------");

192. System.out.println(" 1. Small Pepsi ");


193. System.out.println(" 2. Medium Pepsi
");
194. System.out.println(" 3. Large Pepsi ");
195. System.out.println("------------------------");

196. int pepsisize=Integer.parseInt(br.read


Line());
197. switch(pepsisize)
198. {
199. case 1:
200. itemsOrder.addItems(new SmallPe
psi());
201. break;
202.
203. case 2:
204. itemsOrder.addItems(new Medium
Pepsi());
205. break;
206.
207. case 3:
208. itemsOrder.addItems(new LargePe
psi());
209. break;
210.
211. }
212. }
213. break;
214. case 2:
215. {
216. System.out.println("You ordered Coke");
217. System.out.println("Enter the Coke Size
");
218. System.out.println("------------------------");
219. System.out.println(" 1. Small Coke ");
220. System.out.println(" 2. Medium Coke ");
221. System.out.println(" 3. Large Coke ");

222. System.out.println(" 4. Extra-Large Coke ");

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

Step 15:Create a BuilderDemo class that will use the OrderBuilder


class.

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

download this Builder Pattern Example


Output
Object Pool Pattern
1. Object Pool Pattern
2. Advantage of Object Pool DP
3. Usage of Object Pool DP
4. UML of Object Pool DP
5. Example of Object Pool DP

Mostly, performance is the key issue during the software development


and the object creation, which may be a costly step.

Object Pool Pattern says that " to reuse the object that are expensive
to create".

Basically, an Object pool is a container which contains a specified amount


of objects. When an object is taken from the pool, it is not available in the
pool until it is put back. Objects in the pool have a lifecycle:
creation, validation and destroy.

A pool helps to manage available resources in a better way. There are


many using examples: especially in application servers there are data
source pools, thread pools etc.

Advantage of Object Pool design pattern


o It boosts the performance of the application significantly.
o It is most effective in a situation where the rate of initializing a class
instance is high.
o It manages the connections and provides a way to reuse and share them.
o It can also provide the limit for the maximum number of objects that can
be created.

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.

Example of Object Pool Pattern:


Let's understand the example by the given UML diagram.
UML for Object Pool Pattern
Implementation of above UML:
Step 1

Create an ObjectPool class that is used to create the number of objects.

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

Create an ExportingProcess class that will be used by ExportingTask class.

File: ExportingProcess.java

1. public class ExportingProcess {


2. private long processNo;
3.
4. public ExportingProcess(long processNo) {
5. this.processNo = processNo;
6. // do some expensive calls / tasks here in future
7. // .........
8. System.out.println("Object with process no. " + processNo + " was cre
ated");
9. }
10.
11. public long getProcessNo() {
12. return processNo;
13. }
14.}// End of the ExportingProcess class.
Step 3

Create an ExportingTask class that will use ExportingProcess and


ObjectPool class.

File: ExportingTask.java

1. public class ExportingTask implements Runnable {


2. private ObjectPool<ExportingProcess> pool;
3. private int threadNo;
4. public ExportingTask(ObjectPool<ExportingProcess> pool, int threa
dNo){
5. this.pool = pool;
6. this.threadNo = threadNo;
7. }
8.
9. public void run() {
10. // get an object from the pool
11. ExportingProcess exportingProcess = pool.borrowObje
ct();
12. System.out.println("Thread " + threadNo + ": Object with process
no. "
13. + exportingProcess.getProcessNo() + " was borro
wed");
14.
15. //you can do something here in future
16. // .........
17.
18. // return ExportingProcess instance back to the pool
19. pool.returnObject(exportingProcess);
20.
21. System.out.println("Thread " + threadNo +": Object wi
th process no. "
22. + exportingProcess.getProcessNo() + " was returned");
23. }
24.
25. }// End of the ExportingTask class.
Step 4

Create an ObjectPoolDemo class.

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.

download this Object Pool Pattern Example


Output
Structural design patterns
Structural design patterns are concerned with how classes and objects
can be composed, to form larger structures.

The structural design patterns simplifies the structure by identifying


the relationships.

These patterns focus on, how the classes inherit from each other and how
they are composed from other classes.

Types of structural design patterns


There are following 7 types of structural design patterns.

1. Adapter Pattern

Adapting an interface into another according to client expectation.

2. Bridge Pattern

Separating abstraction (interface) from implementation.

3. Composite Pattern

Allowing clients to operate on hierarchy of objects.

4. Decorator Pattern

Adding functionality to an object dynamically.

5. Facade Pattern

Providing an interface to a set of interfaces.

6. Flyweight Pattern

Reusing an object by sharing it.

7. proxy Pattern

Representing another object.


Adapter Pattern
1. Adapter Design Pattern
2. Advantage of Adapter DP
3. Usage of Adapter DP
4. UML of Adapter DP
5. Example of Adapter DP

An Adapter Pattern says that just "converts the interface of a class


into another interface that a client wants".

In other words, to provide the interface according to client requirement


while using the services of a class with a different interface.

The Adapter Pattern is also known as Wrapper.

Advantage of Adapter Pattern


o It allows two or more previously incompatible objects to interact.
o It allows reusability of existing functionality.

Usage of Adapter pattern:

It is used:

o When an object needs to utilize an existing class with an incompatible


interface.
o When you want to create a reusable class that cooperates with classes
which don't have compatible interfaces.
o When you want to create a reusable class that cooperates with classes
which don't have compatible interfaces.

ADVERTISEMENT BY ADRECOVER

Example of Adapter Pattern


Let's understand the example of adapter design pattern by the above UML
diagram.
UML for Adapter Pattern:

There are the following specifications for the adapter pattern:

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.

Implementation of above UML:


Step 1

Create a CreditCard interface (Target interface).

1. public interface CreditCard {


2. public void giveBankDetails();
3. public String getCreditCard();
4. }// End of the CreditCard interface.
Step 2

Create a BankDetails class (Adaptee class).

File: BankDetails.java

1. // This is the adapter class.


2. public class BankDetails{
3. private String bankName;
4. private String accHolderName;
5. private long accNumber;
6.
7. public String getBankName() {
8. return bankName;
9. }
10. public void setBankName(String bankName) {
11. this.bankName = bankName;
12. }
13. public String getAccHolderName() {
14. return accHolderName;
15. }
16. public void setAccHolderName(String accHolderName) {
17. this.accHolderName = accHolderName;
18. }
19. public long getAccNumber() {
20. return accNumber;
21. }
22. public void setAccNumber(long accNumber) {
23. this.accNumber = accNumber;
24. }
25. }// End of the BankDetails class.
Step 3

Create a BankCustomer class (Adapter class).

File: BankCustomer.java

1. // This is the adapter class


2.
3. import java.io.BufferedReader;
4. import java.io.InputStreamReader;
5. public class BankCustomer extends BankDetails implements Cre
ditCard {
6. public void giveBankDetails(){
7. try{
8. BufferedReader br=new BufferedReader(new InputStreamReader(Syste
m.in));
9.
10. System.out.print("Enter the account holder name :");
11. String customername=br.readLine();
12. System.out.print("\n");
13.
14. System.out.print("Enter the account number:");
15. long accno=Long.parseLong(br.readLine());
16. System.out.print("\n");
17.
18. System.out.print("Enter the bank name :");
19. String bankname=br.readLine();
20.
21. setAccHolderName(customername);
22. setAccNumber(accno);
23. setBankName(bankname);
24. }catch(Exception e){
25. e.printStackTrace();
26. }
27. }
28. @Override
29. public String getCreditCard() {
30. long accno=getAccNumber();
31. String accholdername=getAccHolderName();
32. String bname=getBankName();
33.
34. return ("The Account number "+accno+" of "+accholdername+" in "+b
name+ "
35. bank is valid and authenticated for issuing the
credit card. ");
36. }
37. }//End of the BankCustomer class.
Step 4

Create a AdapterPatternDemo class (client class).

File: AdapterPatternDemo.java

1. //This is the client class.


2. public class AdapterPatternDemo {
3. public static void main(String args[]){
4. CreditCard targetInterface=new BankCustomer();
5. targetInterface.giveBankDetails();
6. System.out.print(targetInterface.getCreditCard());
7. }
8. }//End of the BankCustomer class.

1. Enter the account holder name :Sonoo Jaiswal


2.
3. Enter the account number:10001
4.
5. Enter the bank name :State Bank of India
6.
7. The Account number 10001 of Sonoo Jaiswal in State Bank of India b
ank is valid
8. and authenticated for issuing the credit card.

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

A Bridge Pattern says that just "decouple the functional abstraction


from the implementation so that the two can vary
independently".

The Bridge Pattern is also known as Handle or Body.


Advantage of Bridge Pattern
o It enables the separation of implementation from the interface.
o It improves the extensibility.
o It allows the hiding of implementation details from the client.

Usage of Bridge Pattern


o When you don't want a permanent binding between the functional
abstraction and its implementation.
o When both the functional abstraction and its implementation need to
extended using sub-classes.
o It is mostly used in those places where changes are made in the
implementation does not affect the clients.

ADVERTISEMENT BY ADRECOVER

Example of Bridge Pattern


The UML given below describes the example of bridge pattern.
UML for Bridge Pattern:

Implementation of above UML:


Step 1

Create a Question interface that provides the navigation from one


question to another or vice-versa.

1. // this is the Question interface.


2. public interface Question {
3. public void nextQuestion();
4. public void previousQuestion();
5. public void newQuestion(String q);
6. public void deleteQuestion(String q);
7. public void displayQuestion();
8. public void displayAllQuestions();
9. }
10.// End of the Question interface.
Step 2

Create a JavaQuestions implementation class that will


implement Question interface.

1. // this is the JavaQuestions class.


2. import java.util.ArrayList;
3. import java.util.List;
4. public class JavaQuestions implements Question {
5. private List <String> questions = new ArrayList<String>();
6. private int current = 0;
7. public JavaQuestions(){
8. questions.add("What is class? ");
9. questions.add("What is interface? ");
10. questions.add("What is abstraction? ");
11. questions.add("How multiple polymorphism is achieved in j
ava? ");
12. questions.add("How many types of exception handling are there in java
? ");
13. questions.add("Define the keyword final for variable, meth
od, and class in java? ");
14. questions.add("What is abstract class? ");
15. questions.add("What is multi-threading? ");
16. }
17. public void nextQuestion() {
18. if( current <= questions.size()-1 )
19. current++;
20. System.out.print(current);
21. }
22.
23. public void previousQuestion() {
24. if( current > 0 )
25. current--;
26. }
27.
28. public void newQuestion(String quest) {
29. questions.add(quest);
30. }
31.
32. public void deleteQuestion(String quest) {
33. questions.remove(quest);
34. }
35.
36. public void displayQuestion() {
37. System.out.println( questions.get(current) );
38. }
39. public void displayAllQuestions() {
40. for (String quest : questions) {
41. System.out.println(quest);
42. }
43. }
44.}// End of the JavaQuestions class.
Step 3

Create a QuestionManager class that will use Question interface which


will act as a bridge..

1. // this is the QuestionManager class.


2. public class QuestionManager {
3. protected Question q;
4. public String catalog;
5. public QuestionManager(String catalog) {
6. this.catalog=catalog;
7. }
8. public void next() {
9. q.nextQuestion();
10. }
11. public void previous() {
12. q.previousQuestion();
13. }
14. public void newOne(String quest) {
15. q.newQuestion(quest);
16. }
17. public void delete(String quest) {
18. q.deleteQuestion(quest);
19. }
20. public void display() {
21. q.displayQuestion();
22. }
23. public void displayAll() {
24. System.out.println("Question Paper: " + catalog);
25. q.displayAllQuestions();
26. }
27. }// End of the QuestionManager class.
Step 4

Create a QuestionFormat class that will extend


the QuestionManager class

1. // this is the QuestionFormat class.


2. public class QuestionFormat extends QuestionManager {
3. public QuestionFormat(String catalog){
4. super(catalog);
5. }
6. public void displayAll() {
7. System.out.println("\
n---------------------------------------------------------");
8. super.displayAll();
9. System.out.println("-----------------------------------------------------------"
);
10. }
11. }// End of the QuestionFormat class.
Step 5

Create a BridgePatternDemo class.

1. // this is the BridgePatternDemo class.


2. public class BridgePatternDemo {
3. public static void main(String[] args) {
4. QuestionFormat questions = new QuestionFormat("Java Programming L
anguage");
5. questions.q = new JavaQuestions();
6. questions.delete("what is class?");
7. questions.display();
8. questions.newOne("What is inheritance? ");
9.
10. questions.newOne("How many types of inheritance are there in java?");
11. questions.displayAll();
12. }
13. }// End of the BridgePatternDemo class.

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

A Composite Pattern says that just "allow clients to operate in generic


manner on objects that may or may not represent a hierarchy of
objects".
Advantage of Composite Design Pattern
o It defines class hierarchies that contain primitive and complex objects.
o It makes easier to you to add new kinds of components.
o It provides flexibility of structure with manageable class or interface.

Usage of Composite Pattern

It is used:

o When you want to represent a full or partial hierarchy of objects.


o When the responsibilities are needed to be added dynamically to the
individual objects without affecting other objects. Where the responsibility
of object may vary from time to time.

ADVERTISEMENT BY ADRECOVER

UML for Composite Pattern


Elements used in Composite Pattern:

Let's see the 4 elements of composte pattern.

1) Component

o Declares interface for objects in composition.


o Implements default behavior for the interface common to all classes as
appropriate.
o Declares an interface for accessing and managing its child components.

2) Leaf

o Represents leaf objects in composition. A leaf has no children.


o Defines behavior for primitive objects in the composition.

3) Composite

o Defines behavior for components having children.


o Stores child component.
o Implements child related operations in the component interface.

4) Client

o Manipulates objects in the composition through the component interface.

Note:The work flow of above general UML is as follows.

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.

Example of Composite Pattern


We can easily understand the example of composite design pattern by the
UML diagram given below:
Implementation of above UML:
Step 1

Create an Employee interface that will be treated as a component.

1. // this is the Employee interface i.e. Component.


2. public interface Employee {
3. public int getId();
4. public String getName();
5. public double getSalary();
6. public void print();
7. public void add(Employee employee);
8. public void remove(Employee employee);
9. public Employee getChild(int i);
10.}// End of the Employee interface.
Step 2

Create a BankManager class that will be treated as a Composite and


implements Employee interface.

File: BankManager.java

1. // this is the BankManager class i.e. Composite.


2. import java.util.ArrayList;
3. import java.util.Iterator;
4. import java.util.List;
5. public class BankManager implements Employee {
6. private int id;
7. private String name;
8. private double salary;
9.
10. public BankManager(int id,String name,double salary) {
11. this.id=id;
12. this.name = name;
13. this.salary = salary;
14. }
15. List<Employee> employees = new ArrayList<Employee
>();
16. @Override
17. public void add(Employee employee) {
18. employees.add(employee);
19. }
20. @Override
21. public Employee getChild(int i) {
22. return employees.get(i);
23. }
24. @Override
25. public void remove(Employee employee) {
26. employees.remove(employee);
27. }
28. @Override
29. public int getId() {
30. return id;
31. }
32. @Override
33. public String getName() {
34. return name;
35. }
36. @Override
37. public double getSalary() {
38. return salary;
39. }
40. @Override
41. public void print() {
42. System.out.println("==========================");
43. System.out.println("Id ="+getId());
44. System.out.println("Name ="+getName());
45. System.out.println("Salary ="+getSalary());
46. System.out.println("==========================");
47.
48. Iterator<Employee> it = employees.iterator();
49.
50. while(it.hasNext()) {
51. Employee employee = it.next();
52. employee.print();
53. }
54. }
55. }// End of the BankManager class.
Step 3

Create a Cashier class that will be treated as a leaf and it will implement
to the Employee interface.

File: Cashier.java

1. public class Cashier implements Employee{


2. /*
3. In this class,there are many methods which are not applicable
to cashier because
4. it is a leaf node.
5. */
6. private int id;
7. private String name;
8. private double salary;
9. public Cashier(int id,String name,double salary) {
10. this.id=id;
11. this.name = name;
12. this.salary = salary;
13. }
14. @Override
15. public void add(Employee employee) {
16. //this is leaf node so this method is not applicable to this class.
17. }
18. @Override
19. public Employee getChild(int i) {
20. //this is leaf node so this method is not applicable to this class.
21. return null;
22. }
23. @Override
24. public int getId() {
25. // TODO Auto-generated method stub
26. return id;
27. }
28. @Override
29. public String getName() {
30. return name;
31. }
32. @Override
33. public double getSalary() {
34. return salary;
35. }
36. @Override
37. public void print() {
38. System.out.println("==========================");
39. System.out.println("Id ="+getId());
40. System.out.println("Name ="+getName());
41. System.out.println("Salary ="+getSalary());
42. System.out.println("==========================");
43. }
44. @Override
45. public void remove(Employee employee) {
46. //this is leaf node so this method is not applicable to this class.
47. }
48.}
Step 4

Create a Accountant class that will also be treated as a leaf and it will
implement to the Employee interface.

File: Accountant.java

1. public class Accountant implements Employee{


2. /*
3. In this class,there are many methods which are not applicable to
cashier because
4. it is a leaf node.
5. */
6. private int id;
7. private String name;
8. private double salary;
9. public Accountant(int id,String name,double salary) {
10. this.id=id;
11. this.name = name;
12. this.salary = salary;
13. }
14. @Override
15. public void add(Employee employee) {
16. //this is leaf node so this method is not applicable to this class.
17. }
18. @Override
19. public Employee getChild(int i) {
20. //this is leaf node so this method is not applicable to this class.
21. return null;
22. }
23. @Override
24. public int getId() {
25. // TODO Auto-generated method stub
26. return id;
27. }
28. @Override
29. public String getName() {
30. return name;
31. }
32. @Override
33. public double getSalary() {
34. return salary;
35. }
36. @Override
37. public void print() {
38. System.out.println("=========================");
39. System.out.println("Id ="+getId());
40. System.out.println("Name ="+getName());
41. System.out.println("Salary ="+getSalary());
42. System.out.println("=========================");
43. }
44. @Override
45. public void remove(Employee employee) {
46. //this is leaf node so this method is not applicable to this class.
47. }
48.}
Step 5

Create a CompositePatternDemo class that will also be treated as


a Client and ii will use the Employee interface.

File: CompositePatternDemo.java

1. public class CompositePatternDemo {


2. public static void main(String args[]){
3. Employee emp1=new Cashier(101,"Sohan Kumar", 20000.0);
4. Employee emp2=new Cashier(102,"Mohan Kumar", 25000.0);
5. Employee emp3=new Accountant(103,"Seema Mahiwal", 300
00.0);
6. Employee manager1=new BankManager(100,"Ashwani Rajput",100
000.0);
7.
8. manager1.add(emp1);
9. manager1.add(emp2);
10. manager1.add(emp3);
11. manager1.print();
12. }
13. }

download this composite pattern Example


Output
1. ==========================
2. Id =100
3. Name =Ashwani Rajput
4. Salary =100000.0
5. ==========================
6. ==========================
7. Id =101
8. Name =Sohan Kumar
9. Salary =20000.0
10.==========================
11. ==========================
12.Id =102
13. Name =Mohan Kumar
14.Salary =25000.0
15. ==========================
16.=========================
17. Id =103
18.Name =Seema Mahiwal
19. Salary =30000.0
20.=========================

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".

In other words, The Decorator Pattern uses composition instead of


inheritance to extend the functionality of an object at runtime.

The Decorator Pattern is also known as Wrapper.

Advantage of Decorator Pattern


o It provides greater flexibility than static inheritance.
o It enhances the extensibility of the object, because changes are made by
coding new classes.
o It simplifies the coding by allowing you to develop a series of functionality
from targeted classes instead of coding all of the behavior into the object.

Usage of Decorator Pattern

It is used:

o When you want to transparently and dynamically add responsibilities to


objects without affecting other objects.
o When you want to add responsibilities to an object that you may want to
change in future.
o Extending functionality by sub-classing is no longer practical.

ADVERTISEMENT BY ADRECOVER
UML for Decorator Pattern:

Step 1:Create a Food interface.

1. public interface Food {


2. public String prepareFood();
3. public double foodPrice();
4. }// End of the Food interface.

Step 2: Create a VegFood class that will implements the Food interface
and override its all methods.

File: VegFood.java

1. public class VegFood implements Food {


2. public String prepareFood(){
3. return "Veg Food";
4. }
5.
6. public double foodPrice(){
7. return 50.0;
8. }
9. }

Step 3:Create a FoodDecorator abstract class that will implements the


Food interface and override it's all methods and it has the ability to
decorate some more foods.

File: FoodDecorator.java

1. public abstract class FoodDecorator implements Food{


2. private Food newFood;
3. public FoodDecorator(Food newFood) {
4. this.newFood=newFood;
5. }
6. @Override
7. public String prepareFood(){
8. return newFood.prepareFood();
9. }
10. public double foodPrice(){
11. return newFood.foodPrice();
12. }
13. }

Step 4:Create a NonVegFood concrete class that will extend


the FoodDecorator class and override it's all methods.

File: NonVegFood.java

1. public class NonVegFood extends FoodDecorator{


2. public NonVegFood(Food newFood) {
3. super(newFood);
4. }
5. public String prepareFood(){
6. return super.prepareFood() +" With Roasted Chiken and Chiken Cur
ry ";
7. }
8. public double foodPrice() {
9. return super.foodPrice()+150.0;
10. }
11. }

Step 5:Create a ChineeseFood concrete class that will extend


the FoodDecorator class and override it's all methods.

File: ChineeseFood.java

1. public class ChineeseFood extends FoodDecorator{


2. public ChineeseFood(Food newFood) {
3. super(newFood);
4. }
5. public String prepareFood(){
6. return super.prepareFood() +" With Fried Rice and Manchurian ";
7. }
8. public double foodPrice() {
9. return super.foodPrice()+65.0;
10. }
11. }

Step 6:Create a DecoratorPatternCustomer class that will use Food


interface to use which type of food customer wants means (Decorates).

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. }

1. ========= Food Menu ============


2. 1. Vegetarian Food.
3. 2. Non-Vegetarian Food.
4. 3. Chineese Food.
5. 4. Exit
6. Enter your choice: 1
7. Veg Food
8. 50.0
9. ========= Food Menu ============
10. 1. Vegetarian Food.
11. 2. Non-Vegetarian Food.
12. 3. Chineese Food.
13. 4. Exit
14. Enter your choice: 2
15. Veg Food With Roasted Chiken and Chiken Curry
16. 200.0
17. ========= Food Menu ============
18. 1. Vegetarian Food.
19. 2. Non-Vegetarian Food.
20. 3. Chineese Food.
21. 4. Exit
22. Enter your choice: 3
23. Veg Food With Fried Rice and Manchurian
24. 115.0
25. ========= Food Menu ============
26. 1. Vegetarian Food.
27. 2. Non-Vegetarian Food.
28. 3. Chineese Food.
29. 4. Exit
30. Enter your choice: 4
31. Other than these no food available

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".

In other words, Facade Pattern describes a higher-level interface that


makes the sub-system easier to use.

Practically, every Abstract Factory is a type of Facade.

Advantage of Facade Pattern


o It shields the clients from the complexities of the sub-system components.
o It promotes loose coupling between subsystems and its clients.

Usage of Facade Pattern:

It is used:

o When you want to provide simple interface to a complex sub-system.


o When several dependencies exist between clients and the implementation
classes of an abstraction.

ADVERTISEMENT BY ADRECOVER

Example of Facade Pattern


Let's understand the example of facade design pattern by the above UML
diagram.
UML for Facade Pattern:

Implementation of above UML:


Step 1

Create a MobileShop interface.

File: MobileShop.java

1. public interface MobileShop {


2. public void modelNo();
3. public void price();
4. }
Step 2

Create a Iphone implementation class that will


implement Mobileshop interface.

File: Iphone.java

1. public class Iphone implements MobileShop {


2. @Override
3. public void modelNo() {
4. System.out.println(" Iphone 6 ");
5. }
6. @Override
7. public void price() {
8. System.out.println(" Rs 65000.00 ");
9. }
10.}
Step 3

Create a Samsung implementation class that will


implement Mobileshop interface.

File: Samsung.java

1. public class Samsung implements MobileShop {


2. @Override
3. public void modelNo() {
4. System.out.println(" Samsung galaxy tab 3 ");
5. }
6. @Override
7. public void price() {
8. System.out.println(" Rs 45000.00 ");
9. }
10.}
Step 4

Create a Blackberry implementation class that will


implement Mobileshop interface .

File: Blackberry.java

1. public class Blackberry implements MobileShop {


2. @Override
3. public void modelNo() {
4. System.out.println(" Blackberry Z10 ");
5. }
6. @Override
7. public void price() {
8. System.out.println(" Rs 55000.00 ");
9. }
10.}
Step 5

Create a ShopKeeper concrete class that will use MobileShop interface.

File: ShopKeeper.java

1. public class ShopKeeper {


2. private MobileShop iphone;
3. private MobileShop samsung;
4. private MobileShop blackberry;
5.
6. public ShopKeeper(){
7. iphone= new Iphone();
8. samsung=new Samsung();
9. blackberry=new Blackberry();
10. }
11. public void iphoneSale(){
12. iphone.modelNo();
13. iphone.price();
14. }
15. public void samsungSale(){
16. samsung.modelNo();
17. samsung.price();
18. }
19. public void blackberrySale(){
20. blackberry.modelNo();
21. blackberry.price();
22. }
23. }
Step 6

Now, Creating a client that can purchase the mobiles


from MobileShop through ShopKeeper.

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. }

1. ========= Mobile Shop ============


2. 1. IPHONE.
3. 2. SAMSUNG.
4. 3. BLACKBERRY.
5. 4. Exit.
6. Enter your choice: 1
7. Iphone 6
8. Rs 65000.00
9. ========= Mobile Shop ============
10. 1. IPHONE.
11. 2. SAMSUNG.
12. 3. BLACKBERRY.
13. 4. Exit.
14. Enter your choice: 2
15. Samsung galaxy tab 3
16. Rs 45000.00
17. ========= Mobile Shop ============
18. 1. IPHONE.
19. 2. SAMSUNG.
20. 3. BLACKBERRY.
21. 4. Exit.
22. Enter your choice: 3
23. Blackberry Z10
24. Rs 55000.00
25. ========= Mobile Shop ============
26. 1. IPHONE.
27. 2. SAMSUNG.
28. 3. BLACKBERRY.
29. 4. Exit.
30. Enter your choice: 4
31. Nothing You purchased
Flyweight Pattern
1. Flyweight Design Pattern
2. Advantage of Flyweight DP
3. Usage of Flyweight DP
4. UML of Flyweight DP
5. Example of Flyweight DP

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".

Advantage of Flyweight Pattern


o It reduces the number of objects.
o It reduces the amount of memory and storage devices required if the
objects are persisted

Usage of Flyweight Pattern


o When an application uses number of objects
o When the storage cost is high because of the quantity of objects.
o When the application does not depend on object identity.

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

Simply, proxy means an object representing another object.

According to GoF, a Proxy Pattern "provides the control for accessing


the original object".

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.

Usage of Proxy Pattern:

It is used:

o It can be used in Virtual Proxy scenario---Consider a situation where


there is multiple database call to extract huge size image. Since this is an
expensive operation so here we can use the proxy pattern which would
create multiple proxies and point to the huge size memory consuming
object for further processing. The real object gets created only when a
client first requests/accesses the object and after that we can just refer to
the proxy to reuse the object. This avoids duplication of the object and
hence saving memory.
o It can be used in Protective Proxy scenario---It acts as an authorization
layer to verify that whether the actual user has access the appropriate
content or not. For example, a proxy server which provides restriction on
internet access in office. Only the websites and contents which are valid
will be allowed and the remaining ones will be blocked.
o It can be used in Remote Proxy scenario---A remote proxy can be
thought about the stub in the RPC call. The remote proxy provides a local
representation of the object which is present in the different address
location. Another example can be providing interface for remote resources
such as web service or REST resources.
o It can be used in Smart Proxy scenario---A smart proxy provides
additional layer of security by interposing specific actions when the object
is accessed. For example, to check whether the real object is locked or not
before accessing it so that no other objects can change it.

ADVERTISEMENT BY ADRECOVER

Example of Proxy Pattern


Let's understand the example of proxy design pattern by the above UML
diagram.

UML for Proxy Pattern:

Implementation of above UML:


Step 1

Create an OfficeInternetAccess interface.

1. public interface OfficeInternetAccess {


2. public void grantInternetAccess();
3. }
Step 2

Create a RealInternetAccess class that will


implement OfficeInternetAccess interface for granting the permission to
the specific employee.

File: RealInternetAccess.java

1. public class RealInternetAccess implements OfficeInternetAccess


{
2. private String employeeName;
3. public RealInternetAccess(String empName) {
4. this.employeeName = empName;
5. }
6. @Override
7. public void grantInternetAccess() {
8. System.out.println("Internet Access granted for employee: "+ employ
eeName);
9. }
10.}
Step 3

Create a ProxyInternetAccess class that will


implement OfficeInternetAccess interface for providing the object
of RealInternetAccess class.

File: ProxyInternetAccess.java

1. public class ProxyInternetAccess implements OfficeInternetAcces


s{
2. private String employeeName;
3. private RealInternetAccess realaccess;
4. public ProxyInternetAccess(String employeeName) {
5. this.employeeName = employeeName;
6. }
7. @Override
8. public void grantInternetAccess()
9. {
10. if (getRole(employeeName) > 4)
11. {
12. realaccess = new RealInternetAccess(employeeName);
13. realaccess.grantInternetAccess();
14. }
15. else
16. {
17. System.out.println("No Internet access granted. You
r job level is below 5");
18. }
19. }
20. public int getRole(String emplName) {
21. // Check role from the database based on Name and de
signation
22. // return job level or job designation.
23. return 9;
24. }
25. }
Step 4

Now, Create a ProxyPatternClient class that can access the internet


actually.

File: ProxyPatternClient.java

1. public class ProxyPatternClient {


2. public static void main(String[] args)
3. {
4. OfficeInternetAccess access = new ProxyInternetAccess("Ashwani Ra
jput");
5. access.grantInternetAccess();
6. }
7. }

No Internet access granted. Your job level is below 5

Behavioral Design Patterns


Behavioral design patterns are concerned with the interaction and
responsibility of objects.

In these design patterns, the interaction between the objects should


be in such a way that they can easily talk to each other and still
should be loosely coupled.

That means the implementation and the client should be loosely coupled
in order to avoid hard coding and dependencies.

There are 12 types of behavioral design patterns:

1. Chain of Responsibility Pattern


2. Command Pattern
3. Interpreter Pattern
4. Iterator Pattern
5. Mediator Pattern
6. Memento Pattern
7. Observer Pattern
8. State Pattern
9. Strategy Pattern
10.Template Pattern
11.Visitor Pattern
12.Null Object

Chain Of Responsibility Pattern


1. Chain Of Responsibility Pattern
2. Advantage of Chain Of Responsibility DP
3. Usage of Chain Of Responsibility DP
4. UML of Chain Of Responsibility DP
5. Example of Chain Of Responsibility DP

In chain of responsibility, sender sends a request to a chain of objects. The


request can be handled by any object in the chain.

A Chain of Responsibility Pattern says that just "avoid coupling the


sender of a request to its receiver by giving multiple objects a
chance to handle the request". For example, an ATM uses the Chain of
Responsibility design pattern in money giving process.

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.

Advantage of Chain of Responsibility Pattern


o It reduces the coupling.
o It adds flexibility while assigning the responsibilities to objects.
o It allows a set of classes to act as one; events produced in one class can
be sent to other handler classes with the help of composition.
Usage of Chain of Responsibility Pattern:

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

Example of Chain of Responsibility Pattern


Let's understand the example of Chain of Responsibility Pattern by the
above UML diagram.

UML for Chain of Responsibility Pattern:

Implementation of above UML:


Step 1

Create a Logger abstract class.

1. public abstract class Logger {


2. public static int OUTPUTINFO=1;
3. public static int ERRORINFO=2;
4. public static int DEBUGINFO=3;
5. protected int levels;
6. protected Logger nextLevelLogger;
7. public void setNextLevelLogger(Logger nextLevelLogger) {
8. this.nextLevelLogger = nextLevelLogger;
9. }
10. public void logMessage(int levels, String msg){
11. if(this.levels<=levels){
12. displayLogInfo(msg);
13. }
14. if (nextLevelLogger!=null) {
15. nextLevelLogger.logMessage(levels, msg);
16. }
17. }
18. protected abstract void displayLogInfo(String msg);
19. }
Step 2

Create a ConsoleBasedLogger class.

File: ConsoleBasedLogger.java

1. public class ConsoleBasedLogger extends Logger {


2. public ConsoleBasedLogger(int levels) {
3. this.levels=levels;
4. }
5. @Override
6. protected void displayLogInfo(String msg) {
7. System.out.println("CONSOLE LOGGER INFO: "+msg);
8. }
9. }
Step 3

Create a DebugBasedLogger class.

File: DebugBasedLogger.java

1. public class DebugBasedLogger extends Logger {


2. public DebugBasedLogger(int levels) {
3. this.levels=levels;
4. }
5. @Override
6. protected void displayLogInfo(String msg) {
7. System.out.println("DEBUG LOGGER INFO: "+msg);
8. }
9. }// End of the DebugBasedLogger class.
Step 4

Create a ErrorBasedLogger class.

File: ErrorBasedLogger.java

1. public class ErrorBasedLogger extends Logger {


2. public ErrorBasedLogger(int levels) {
3. this.levels=levels;
4. }
5. @Override
6. protected void displayLogInfo(String msg) {
7. System.out.println("ERROR LOGGER INFO: "+msg);
8. }
9. }// End of the ErrorBasedLogger class.
Step 5

Create a ChainOfResponsibilityClient class.

File: ChainofResponsibilityClient.java

1. public class ChainofResponsibilityClient {


2. private static Logger doChaining(){
3. Logger consoleLogger = new ConsoleBasedLogger(Logger.OU
TPUTINFO);
4.
5. Logger errorLogger = new ErrorBasedLogger(Logger.ERRORI
NFO);
6. consoleLogger.setNextLevelLogger(errorLogger);
7.
8. Logger debugLogger = new DebugBasedLogger(Logger.DEBUGINFO
);
9. errorLogger.setNextLevelLogger(debugLogger);
10.
11. return consoleLogger;
12. }
13. public static void main(String args[]){
14. Logger chainLogger= doChaining();
15.
16. chainLogger.logMessage(Logger.OUTPUTINFO, "Enter the sequen
ce of values ");
17. chainLogger.logMessage(Logger.ERRORINFO, "An err
or is occured now");
18. chainLogger.logMessage(Logger.DEBUGINFO, "This was the error
now debugging is compeled");
19. }
20.}

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

A Command Pattern says that "encapsulate a request under an object as


a command and pass it to invoker object. Invoker object looks for the
appropriate object which can handle this command and pass the
command to the corresponding object and that object executes the
command".

It is also known as Action or Transaction.

Advantage of command pattern


o It separates the object that invokes the operation from the object that
actually performs the operation.
o It makes easy to add new commands, because existing classes remain
unchanged.

Usage of command pattern:

It is used:

o When you need parameterize objects according to an action perform.


o When you need to create and execute requests at different times.
o When you need to support rollback, logging or transaction functionality.

ADVERTISEMENT BY ADRECOVER

Example of command pattern


Let's understand the example of adapter design pattern by the above UML
diagram.

UML for command pattern:


These are the following participants of the Command Design pattern:
o Command This is an interface for executing an operation.
o ConcreteCommand This class extends the Command interface and
implements the execute method. This class creates a binding between the
action and the receiver.
o Client This class creates the ConcreteCommand class and associates it
with the receiver.
o Invoker This class asks the command to carry out the request.
o Receiver This class knows to perform the operation.
Implementation of above UML:
Step 1

Create a ActionListernerCommand interface that will act as a


Command.

1. public interface ActionListenerCommand {


2. public void execute();
3. }
Step 2

Create a Document class that will act as a Receiver.

File: Document.java

1. public class Document {


2. public void open(){
3. System.out.println("Document Opened");
4. }
5. public void save(){
6. System.out.println("Document Saved");
7. }
8. }
Step 3

Create a ActionOpen class that will act as an ConcreteCommand.

File: ActionOpen.java

1. public class ActionOpen implements ActionListenerCommand{


2. private Document doc;
3. public ActionOpen(Document doc) {
4. this.doc = doc;
5. }
6. @Override
7. public void execute() {
8. doc.open();
9. }
10.}
Step 4

Create a ActionSave class that will act as an ConcreteCommand.

File: AdapterPatternDemo.java

1. public class ActionSave implements ActionListenerCommand{


2. private Document doc;
3. public ActionSave(Document doc) {
4. this.doc = doc;
5. }
6. @Override
7. public void execute() {
8. doc.save();
9. }
10.}
Step 5

Create a MenuOptions class that will act as an Invoker.

File: ActionSave.java

1. public class ActionSave implements ActionListenerCommand{


2. private Document doc;
3. public ActionSave(Document doc) {
4. this.doc = doc;
5. }
6. @Override
7. public void execute() {
8. doc.save();
9. }
10.}
Step 6

Create a CommanPatternClient class that will act as a Client.

File: AdapterPatternDemo.java

1. public class CommandPatternClient {


2. public static void main(String[] args) {
3. Document doc = new Document();
4.
5. ActionListenerCommand clickOpen = new ActionOpen(doc);
6. ActionListenerCommand clickSave = new ActionSave(doc);
7.
8. MenuOptions menu = new MenuOptions(clickOpen, clickSave);
9.
10. menu.clickOpen();
11. menu.clickSave();
12. }
13. }

14. Document Opened


15. Document Saved

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

An Interpreter Pattern says that "to define a representation of


grammar of a given language, along with an interpreter that uses
this representation to interpret sentences in the language".

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.

SQL Parsing uses interpreter design pattern.

Advantage of Interpreter Pattern


o It is easier to change and extend the grammar.
o Implementing the grammar is straightforward.

Usage of Interpreter pattern:

It is used:

o When the grammar of the language is not complicated.


o When the efficiency is not a priority.

ADVERTISEMENT BY ADRECOVER

Example of Interpreter Pattern


Let's understand the example of Interpreter Pattern by the above UML
diagram.
UML for Interpreter Pattern:

Implementation of above UML


Step 1

Create a Pattern interface.

1. public interface Pattern {


2. public String conversion(String exp);
3. }
Step 2

Create a InfixToPostfixPattern class that will allow what kind of pattern


you want to convert.

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

Create a InterpreterPatternClient class that will use InfixToPostfix


Conversion.

File: InterpreterPatternClient.java

1. public class InterpreterPatternClient {


2. public static void main(String[] args)
3. {
4. String infix = "a+b*c";
5.
6. InfixToPostfixPattern ip=new InfixToPostfixPattern();
7.
8. String postfix = ip.conversion(infix);
9. System.out.println("Infix: " + infix);
10. System.out.println("Postfix: " + postfix);
11. }
12.}

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

According to GoF, Iterator Pattern is used "to access the elements of


an aggregate object sequentially without exposing its underlying
implementation".

The Iterator pattern is also known as Cursor.

In collection framework, we are now using Iterator that is preferred over


Enumeration.

java.util.Iterator interface uses Iterator Design Pattern.


Advantage of Iterator Pattern
o It supports variations in the traversal of a collection.
o It simplifies the interface to the collection.

Usage of Iterator Pattern:

It is used:

o When you want to access a collection of objects without exposing its


internal representation.
o When there are multiple traversals of objects need to be supported in the
collection.

ADVERTISEMENT BY ADRECOVER

Example of Iterator Pattern


Let's understand the example of iterator pattern pattern by the above
UML diagram.
UML for Iterator Pattern:

Implementation of above UML


Step 1

Create a Iterartor interface.

1. public interface Iterator {


2. public boolean hasNext();
3. public Object next();
4. }
Step 2

Create a Container interface.

1. public interface Container {


2. public Iterator getIterator();
3. }// End of the Iterator interface.
Step 3

Create a CollectionofNames class that will


implement Container interface.

File: CollectionofNames.java

1. public class CollectionofNames implements Container {


2. public String name[]={"Ashwani Rajput", "Soono Jaiswal","Rishi Kumar","
Rahul Mehta","Hemant Mishra"};
3.
4. @Override
5. public Iterator getIterator() {
6. return new CollectionofNamesIterate() ;
7. }
8. private class CollectionofNamesIterate implements Iterator{
9. int i;
10. @Override
11. public boolean hasNext() {
12. if (i<name.length){
13. return true;
14. }
15. return false;
16. }
17. @Override
18. public Object next() {
19. if(this.hasNext()){
20. return name[i++];
21. }
22. return null;
23. }
24. }
25. }
26.}
Step 4

Create a IteratorPatternDemo class.

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".

I will explain the Mediator pattern by considering a problem. When we


begin with development, we have a few classes and these classes interact
with each other producing results. Now, consider slowly, the logic
becomes more complex when functionality increases. Then what
happens? We add more classes and they still interact with each other but
it gets really difficult to maintain this code now. So, Mediator pattern takes
care of this problem.

Mediator pattern is used to reduce communication complexity between


multiple objects or classes. This pattern provides a mediator class which
normally handles all the communications between different classes and
supports easy maintainability of the code by loose coupling.
Benefits:

o It decouples the number of classes.


o It simplifies object protocols.
o It centralizes the control.
o The individual components become simpler and much easier to deal with
because they don't need to pass messages to one another.

The components don't need to contain logic to deal with their


intercommunication and therefore, they are more generic.

Usage:

o It is commonly used in message-based systems likewise chat applications.


o When the set of objects communicate in complex but in well-defined ways.

ADVERTISEMENT BY ADRECOVER

UML for Mediator Pattern:

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

Implementation of Mediator Pattern:


Step 1:

Create a ApnaChatRoom interface.

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:

Create a ApnaChatRoomIml class that will implement ApnaChatRoom


interface and will also use the number of participants involved in chatting
through Participant interface.

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:

Create a Participant abstract class.

1. //This is an abstract class.


2. public abstract class Participant {
3. public abstract void sendMsg(String msg);
4. public abstract void setname(String name);
5. public abstract String getName();
6. }// End of the Participant abstract class.

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:

Create a MediatorPatternDemo class that will use participants involved in


chatting.

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.

The Memento pattern is also known as Token.

Undo or backspace or ctrl+z is one of the most used operation in an


editor. Memento design pattern is used to implement the undo operation.
This is done by saving the current state of the object as it changes state.

Benefits:
o It preserves encapsulation boundaries.
o It simplifies the originator.

Usage:

o It is used in Undo and Redo operations in most software.


o It is also used in database transactions.

ADVERTISEMENT BY ADRECOVER

UML for Memento Pattern:

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:

o Creates a memento object that will capture the internal state of


Originator.
o Use the memento object to restore its previous state.

Caretaker:

o Responsible for keeping the memento.


o The memento is transparent to the caretaker, and the caretaker must not
operate on it.

ADVERTISEMENT BY ADRECOVER

Implementation of Memento Pattern:


Step 1:

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){

20. state = Memento.getState();


21. }
22.}// End of the Originator class.

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:

Create a MementoPatternDemo class.

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".

The observer pattern is also known as Dependents or Publish-Subscribe.

Benefits:

o It describes the coupling between the objects and the observer.


o It provides the support for broadcast-type communication.

Usage:

o When the change of a state in one object must be reflected in another


object without keeping the objects tight coupled.
o When the framework we writes and needs to be enhanced in future with
new observers with minimal chamges.

ADVERTISEMENT BY ADRECOVER

UML for Observer Pattern:


ADVERTISEMENT BY ADRECOVER

Implementation of Observer Pattern


Step 1:

Create a ResponseHandler1 class the will implement the java.util.Observer


interface.

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:

Create a ResponseHandler2 class the will implement the


java.util.Observer interface.

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:

Create an EventSource class that will extend the java.util.Observable class .

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.

The State Pattern is also known as Objects for States.


Benefits:

o It keeps the state-specific behavior.


o It makes any state transitions explicit.

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

UML for State Pattern:

ADVERTISEMENT BY ADRECOVER

Implementation of State Pattern:


Step 1:
Create a Connection interface that will provide the connection to the
Controller class.

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:

Create an Accounting class that will implement to the Connection interface.

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:

Create a Sales class that will implement to the Connection interface.

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:

Create a Sales class that will implement to the Connection interface.

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:

Create a Management class that will implement to the Connection interface.

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:

Create a StatePatternDemo class.

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".

The Strategy Pattern is also known as Policy.

Benefits:

o It provides a substitute to subclassing.


o It defines each behavior within its own class, eliminating the need for
conditional statements.
o It makes it easier to extend and incorporate new behavior without
changing the application.

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

Strategy Pattern in (Core Java API's) or JSE 7 API's:

Strategy Pattern in (Advance Java API's) or JEE 7 API's:


UML for Strategy Pattern:

ADVERTISEMENT BY ADRECOVER

Implementation of Strategy Pattern:


Step 1:

Create a Strategy interface.

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:

Create a Addition class that will implement Startegy interface.

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:

Create a Subtraction class that will implement Startegy interface.

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:

Create a Multiplication class that will implement Startegy interface.

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:

Create a StartegyPatternDemo class.

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:

o It is used when the common behavior among sub-classes should be moved


to a single common class by avoiding the duplication.

ADVERTISEMENT BY ADRECOVER

UML for Template Pattern:

ADVERTISEMENT BY ADRECOVER

Implementation of Template Pattern:


Step 1:
Create a Game abstract class.

1. //This is an abstract class.


2. public abstract class Game {
3.
4. abstract void initialize();
5. abstract void start();
6. abstract void end();
7.
8. public final void play(){
9.
10. //initialize the game
11. initialize();
12.
13. //start game
14. start();
15.
16. //end game
17. end();
18. }
19. }// End of the Game abstract class.

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:

Create a TemplatePatternDemo class.

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:

JEE or J2EE Design Patterns


J2EE design patterns are built for the developing the Enterprise Web-
based Applications.

In J2EE , there are mainly three types of design patterns, which are further
divided into their sub-parts:
1. Presentation Layer Design Pattern

1. Intercepting Filter Pattern


2. Front Controller Pattern
3. View Helper Pattern
4. Composite View Pattern

2. Business Layer Design Pattern

1. Business Delegate Pattern


2. Service Locator Pattern
3. Session Facade Pattern
4. Transfer Object Pattern

3. Integration Layer Design Pattern

1. Data Access Object Pattern


2. Web Service Broker Pattern

Presentation Layer

Intercepting Filter Pattern


An Intercepting Filter Pattern says that "if you want to intercept and
manipulate a request and response before and after the request is
processed".

Usage:

o When you want centralization, common processing across requests, such


as logging information about each request, compressing an outgoing
response or checking the data encoding scheme of each request.
o When you want pre and post processing the components which are loosely
coupled with core request-handling services to facilitate which are not
suitable for addition and removal.
Benefits:

o It provides central control with loosely coupled handlers.


o It improves reusability.

ADVERTISEMENT BY ADRECOVER

UML for Intercepting Filter Pattern:

ADVERTISEMENT BY ADRECOVER

Implementation of Intercepting Filter Pattern:


Step 1

Create a Login.html web page.

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

Create a LoginServlet class.

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

Create a LoginSuccess.jsp page.


1. <%@ page language="java" contentType="text/html; charset=US-
ASCII"
2. pageEncoding="US-ASCII"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=US-
ASCII">
7. <title>Login Success Page</title>
8. </head>
9. <body>
10.<%
11. //allow access only if session exists
12.String user = (String) session.getAttribute("user");
13. String userName = null;
14.String sessionID = null;
15. Cookie[] cookies = request.getCookies();
16.if(cookies !=null){
17. for(Cookie cookie : cookies){
18. if(cookie.getName().equals("user")) userName = cookie.getValue();
19. if(cookie.getName().equals("JSESSIONID")) sessionID = coo
kie.getValue();
20.}
21. }
22.%>
23. <h3>Hi <%=userName %>, Login successful.Your Session ID
=<%=sessionID %></h3>
24.<br>
25. User=<%=user %>
26.<br>
27. <a href="CheckoutPage.jsp">Checkout Page</a><br>
28.<form action="LogoutServlet" method="post">
29. <input type="submit" value="Logout" >
30.</form>
31. </body>
32.</html>
Step 4

Create an AdminPage.jsp page.

1. <%@ page language="java" contentType="text/html; charset=US-


ASCII"
2. pageEncoding="US-ASCII"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=US-
ASCII">
7. <title>Login Success Page</title>
8. </head>
9. <body>
10.<%
11. String userName = null;
12.String sessionID = null;
13. Cookie[] cookies = request.getCookies();
14.if(cookies !=null){
15. for(Cookie cookie : cookies){
16. if(cookie.getName().equals("user")) userName = cookie.getValue();
17. }
18.}
19. %>
20.<h3>Hi <%=userName %>, These services are only for you to take actio
n.</h3>
21. <br>
22.<form action="LogoutServlet" method="post">
23. <input type="submit" value="Logout" >
24.</form>
25. </body>
26.</html>

Step 5

Create an LogoutServlet class.


1. package sessions;
2.
3. import java.io.IOException;
4.
5. import javax.servlet.ServletException;
6. import javax.servlet.annotation.WebServlet;
7. import javax.servlet.http.Cookie;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10.import javax.servlet.http.HttpServletResponse;
11. import javax.servlet.http.HttpSession;
12.
13. /**
14. * Servlet implementation class LogoutServlet
15. */
16.@WebServlet("/LogoutServlet")
17. public class LogoutServlet extends HttpServlet {
18. private static final long serialVersionUID = 1L;
19.
20. protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
21. response.setContentType("text/html");
22. Cookie[] cookies = request.getCookies();
23. if(cookies != null){
24. for(Cookie cookie : cookies){
25. if(cookie.getName().equals("JSESSIONID")){
26. System.out.println("JSESSIONID="+cookie.getValue());
27. break;
28. }
29. }
30. }
31. //invalidate the session if exists
32. HttpSession session = request.getSession(false);
33. System.out.println("User="+session.getAttribute("user"))
;
34. if(session != null){
35. session.invalidate();
36. }
37. response.sendRedirect("Login.html");
38. }
39.
40.}//End of the LogoutServlet class

Step 6

Create an AuthenticationFilter class.

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

Create an RequestLoggingFilter class.

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

Create a web.xml file.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xm
lns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://
java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" version="3.0">
3. <display-name>ServletFilterExample</display-name>
4. <welcome-file-list>
5. <welcome-file>Login.html</welcome-file>
6. </welcome-file-list>
7. <filter>
8. <filter-name>RequestLoggingFilter</filter-name>
9. <filter-class>filters.RequestLoggingFilter</filter-class>
10. </filter>
11. <filter>
12. <filter-name>AuthenticationFilter</filter-name>
13. <filter-class>filters.AuthenticationFilter</filter-class>
14. </filter>
15. <filter-mapping>
16. <filter-name>RequestLoggingFilter</filter-name>
17. <url-pattern>/*</url-pattern>
18. <dispatcher>REQUEST</dispatcher>
19. </filter-mapping>
20. <filter-mapping>
21. <filter-name>AuthenticationFilter</filter-name>
22. <url-pattern>/*</url-pattern>
23. </filter-mapping>
24.</web-app>

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:

o It reduces the duplication of code in JSP pages, especially in those cases


where several resources require the same processing.
o It maintains and controls a web application more effectively.
o A web application of two-tier architecture, the recommended approach is
front controller to deal with user requests.

ADVERTISEMENT BY ADRECOVER

UML for Front Controller Pattern:

ADVERTISEMENT BY ADRECOVER

Implementation of Front Controller Pattern:


Step 1
Create a Login.html web page.

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

Create a FrontControllerServlet.java class which is a servlet and it may be a


JSP page also.

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

Create a Success.jsp page.

1. <%@ page language="java" contentType="text/html; charset=ISO-


8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
7. <title>Welcome Page</title>
8. </head>
9. <body style="background-color: gray;">
10.
11. <% String name=request.getParameter("username"); %>
12.
13. <b>Welcome,</b> <% out.print(name); %>
14.
15. </body>
16.</html>

Step 4

Create a Error.jsp page.

1. <%@ page language="java" contentType="text/html; charset=ISO-


8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
7. <title>Insert title here</title>
8. </head>
9. <body style="background-color: olive;">
10.
11. <b>You are have entered wrong username or password!!
</b><br>
12.
13. <a href="Login.html">Back To Home Page</a>
14.</body>
15. </html>

Step 5

Create a web.xml file.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml
ns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://
java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" version="3.0">
3. <display-name>Front Controller Example</display-name>
4. <welcome-file-list>
5. <welcome-file>Login.html</welcome-file>
6. </welcome-file-list>
7. </web-app>

Output:

You might also like