Design Patterns
Design Patterns
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.
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.
2. They provide the solutions that help to define the system architecture.
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.
Design patterns ease the analysis and requirement phase of SDLC by providing information
based on prior hands-on experiences.
1. Factory Pattern
3. Singleton Pattern
4. Prototype Pattern
5. Builder Pattern.
1. Adapter Pattern
2. Bridge Pattern
3. Composite Pattern
4. Decorator Pattern
5. Facade Pattern
6. Flyweight Pattern
7. Proxy Pattern
Design
Design Patterns
Patterns Index
Index
Do you know?
Christopher Alexander was the first person who invented all the above Design
Patterns in 1977.
Home Core Java Servlet JSP Struts2 Mail API Hibernate Spring Android
But everyone knows an object is created by using new keyword in java. For example:
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.
3. Singleton Pattern
4. Prototype Pattern
5. Builder Pattern
← Prev
Next →
For Videos Join Our Youtube Channel: Join Now
Feedback
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.
Factory Method Pattern allows the sub-classes to choose the type of objects to create.
When a class wants that its sub-classes specify the objects to be created.
When the parent classes choose the creation of objects to its sub-classes.
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.
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
import java.io.*;
abstract class Plan{
protected double rate;
abstract void getRate();
public void calculateBill(int units){
System.out.println(units*rate);
}
}//end of Plan class.
Step 2: Create the concrete classes that extends Plan abstract class.
class DomesticPlan extends Plan{
//@override
public void getRate(){
rate=3.50;
}
}//end of DomesticPlan class.
class CommercialPlan extends Plan{
//@override
public void getRate(){
rate=7.50;
}
/end of CommercialPlan class.
class InstitutionalPlan extends Plan{
//@override
public void getRate(){
rate=5.50;
}
/end of InstitutionalPlan class.
class GetPlanFactory{
//use getPlan method to get object of type Plan
public Plan getPlan(String planType){
if(planType == null){
return null;
}
if(planType.equalsIgnoreCase("DOMESTICPLAN")) {
return new DomesticPlan();
}
else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){
return new CommercialPlan();
}
else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
return new InstitutionalPlan();
}
return null;
}
}//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.
import java.io.*;
class GenerateBill{
public static void main(String args[])throws IOException{
GetPlanFactory planFactory = new GetPlanFactory();
System.out.print("Enter the name of plan for which the bill will be generated: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String planName=br.readLine();
System.out.print("Enter the number of units for bill will be calculated: ");
int units=Integer.parseInt(br.readLine());
Plan p = planFactory.getPlan(planName);
//call getRate() method and calculateBill()method of DomesticPaln.
System.out.print("Bill amount for "+planName+" of "+units+" units is: ");
p.getRate();
p.calculateBill(units);
}
}//end of GenerateBill class.
Output
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Feedback
Abstract Factory Pattern isolates the client code from concrete (implementation) classes.
It eases the exchanging of object families.
It promotes consistency among objects.
When the system needs to be independent of how its object are created, composed, and
represented.
When the family of related objects has to be used together, then this constraint needs to
be enforced.
When you want to provide a library of objects that does not show implementations and
only reveals interfaces.
When the system needs to be configured with one of a multiple family of objects.
We are going to create a Bank interface and a Loan abstract class as well as their sub-
classes.
Then we will create AbstractFactory class as next step.
Then after we will create concrete classes, BankFactory, and LoanFactory that will
extends AbstractFactory class
After that, AbstractFactoryPatternExample class uses the FactoryCreator to get an
object of AbstractFactory class.
See the diagram carefully which is given below:
⇧ SCROLL TO TOP
Example of Abstract Factory Pattern
Here, we are calculating the loan payment for different banks like HDFC, ICICI, SBI etc.
import java.io.*;
interface Bank{
String getBankName();
}
class HDFC implements Bank{
⇧ SCROLL TO TOP
private final String BNAME;
public HDFC(){
BNAME="HDFC BANK";
}
public String getBankName() {
return BNAME;
}
}
class ICICI implements Bank{
private final String BNAME;
ICICI(){
BNAME="ICICI BANK";
}
public String getBankName() {
return BNAME;
}
}
class SBI implements Bank{
private final String BNAME;
public SBI(){
BNAME="SBI BANK";
}
public String getBankName(){
return BNAME;
}
}
abstract class Loan{
protected double rate;
abstract void getInterestRate(double rate);
public void calculateLoanPayment(double loanamount, int years)
{
/* TO TOP
⇧ SCROLL
to calculate the monthly loan payment i.e. EMI
rate=annual interest rate/12*100;
n=number of monthly installments;
1year=12 months.
so, n=years*12;
*/
double EMI;
int n;
n=years*12;
rate=rate/1200;
EMI=((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-1))*loanamount;
System.out.println("your monthly EMI is "+ EMI +" for the amount"+loanamount+" you have bor
}
}// end of the Loan abstract class.
Step 4: Create concrete classes that extend the Loan abstract class..
class HomeLoan extends Loan{
public void getInterestRate(double r){
rate=r;
}
}//End of the HomeLoan class.
class BussinessLoan extends Loan{
public void getInterestRate(double r){
rate=r;
}
}//End of the BusssinessLoan class.
class EducationLoan
⇧ SCROLL TO TOP extends Loan{
public void getInterestRate(double r){
rate=r;
}
}//End of the EducationLoan class.
Step 5: Create an abstract class (i.e AbstractFactory) to get the factories for Bank and Loan
Objects.
abstract class AbstractFactory{
public abstract Bank getBank(String bank);
public abstract Loan getLoan(String loan);
}
Step 6: Create the factory classes that inherit AbstractFactory class to generate the object of
concrete class based on given information.
class BankFactory extends AbstractFactory{
public Bank getBank(String bank){
if(bank == null){
return null;
}
if(bank.equalsIgnoreCase("HDFC")){
return new HDFC();
} else if(bank.equalsIgnoreCase("ICICI")){
return new ICICI();
} else if(bank.equalsIgnoreCase("SBI")){
return new SBI();
}
return null;
}
public Loan getLoan(String loan) {
return null;
}
}//End of the BankFactory class.
class LoanFactory extends AbstractFactory{
⇧ SCROLL TO TOP
public Bank getBank(String bank){
return null;
}
public Loan getLoan(String loan){
if(loan == null){
return null;
}
if(loan.equalsIgnoreCase("Home")){
return new HomeLoan();
} else if(loan.equalsIgnoreCase("Business")){
return new BussinessLoan();
} else if(loan.equalsIgnoreCase("Education")){
return new EducationLoan();
}
return null;
}
}
Step 7: Create a FactoryCreator class to get the factories by passing an information such as
Bank or Loan.
class FactoryCreator {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("Bank")){
return new BankFactory();
} else if(choice.equalsIgnoreCase("Loan")){
return new LoanFactory();
}
return null;
}
}//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.
⇧ SCROLL TO TOP
import java.io.*;
class AbstractFactoryPatternExample {
public static void main(String args[])throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the name of Bank from where you want to take loan amount: ");
String bankName=br.readLine();
System.out.print("\n");
System.out.print("Enter the type of loan e.g. home loan or business loan or education loan : ");
String loanName=br.readLine();
AbstractFactory bankFactory = FactoryCreator.getFactory("Bank");
Bank b=bankFactory.getBank(bankName);
System.out.print("\n");
System.out.print("Enter the interest rate for "+b.getBankName()+ ": ");
double rate=Double.parseDouble(br.readLine());
System.out.print("\n");
System.out.print("Enter the loan amount you want to take: ");
double loanAmount=Double.parseDouble(br.readLine());
System.out.print("\n");
System.out.print("Enter the number of years to pay your entire loan amount: ");
int years=Integer.parseInt(br.readLine());
System.out.print("\n");
System.out.println("you are taking the loan from "+ b.getBankName());
AbstractFactory loanFactory = FactoryCreator.getFactory("Loan");
Loan l=loanFactory.getLoan(loanName);
l.getInterestRate(rate);
l.calculateLoanPayment(loanAmount,years);
}
⇧ SCROLL TO TOP
}//End of the AbstractFactoryPatternExample
download this Abstract Factory Pattern Example
Output
← Prev
Next →
For Videos Join Our Youtube Channel: Join Now
Feedback
⇧ SCROLL TO TOP
Splunk SPSS Swagger Transact-SQL
Singleton design pattern in Java
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.
Saves memory because object is not created at each request. Only single
instance is reused again and again.
To create the singleton class, we need to have static member of class, private
constructor and static factory method.
Static member: It gets memory only once because of static, itcontains the
instance of the Singleton class.
Private constructor: It will prevent to instantiate the Singleton class from outside
the class.
Static factory method: This provides the global point of access to the Singleton
object and returns the instance to the caller.
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
class A{
private static A obj=new A();//Early, instance will be created at load time
private A(){}
public static A getA(){
return obj;
}
public void doSomething(){
//write your code
}
}
Let's see the simple example of singleton design pattern using lazy instantiation.
File: A.java
class A{
private static A obj;
private A(){}
public static A getA(){
if (obj == null){
synchronized(Singleton.class){
if (obj == null){
obj = new Singleton();//instance will be created at request time
}
}
}
return obj;
}
public void doSomething(){
//write your code
}
}
If singleton class is loaded by two classloaders, two instance of singleton class will be
created, one for each classloader.
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.
public class A implements Serializable {
//your code of singleton
protected Object readResolve() {
return getA();
}
}
File: JDBCSingleton.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class JDBCSingleton {
//Step 1
// create a JDBCSingleton class.
//static member holds only one instance of the JDBCSingleton class.
private static JDBCSingleton jdbc;
//JDBCSingleton prevents the instantiation from any other class.
private JDBCSingleton() { }
//Now we are providing gloabal point of access.
public static JDBCSingleton getInstance() {
if (jdbc==null)
{
jdbc=new JDBCSingleton();
}
return jdbc;
}
// to get the connection from methods like insert, view etc.
private static Connection getConnection()throws ClassNotFoundException, SQLExceptio
{
Connection con=null;
Class.forName("com.mysql.jdbc.Driver");
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/ashwanirajput", "root
return con;
}
//to insert the record into the database
public int insert(String name, String pass) throws SQLException
{
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement("insert into userdata(uname,upassword)values(?,?)");
ps.setString(1, name);
ps.setString(2, pass);
recordCounter=ps.executeUpdate();
} catch (Exception e) { e.printStackTrace(); } finally{
if (ps!=null){
ps.close();
}if(c!=null){
c.close();
}
}
return recordCounter;
}
//to view the data from the database
public void view(String name) throws SQLException
{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con=this.getConnection();
ps=con.prepareStatement("select * from userdata where uname=?");
ps.setString(1, name);
rs=ps.executeQuery();
while (rs.next()) {
System.out.println("Name= "+rs.getString(2)+"\t"+"Paasword= "+rs.getStrin
}
} catch (Exception e) { System.out.println(e);}
finally{
if(rs!=null){
rs.close();
}if (ps!=null){
ps.close();
}if(con!=null){
con.close();
}
}
}
// to update the password for the given username
public int update(String name, String password) throws SQLException {
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement(" update userdata set upassword=? where uname='"+nam
ps.setString(1, password);
recordCounter=ps.executeUpdate();
} catch (Exception e) { e.printStackTrace(); } finally{
if (ps!=null){
ps.close();
}if(c!=null){
c.close();
}
}
return recordCounter;
}
// to delete the data from the database
public int delete(int userid) throws SQLException{
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement(" delete from userdata where uid='"+userid+"' ");
recordCounter=ps.executeUpdate();
} catch (Exception e) { e.printStackTrace(); }
finally{
if (ps!=null){
ps.close();
}if(c!=null){
c.close();
}
}
return recordCounter;
}
}// End of JDBCSingleton class
File: JDBCSingletonDemo.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class JDBCSingletonDemo{
static int count=1;
static int choice;
public static void main(String[] args) throws IOException {
JDBCSingleton jdbc= JDBCSingleton.getInstance();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do{
System.out.println("DATABASE OPERATIONS");
System.out.println(" --------------------- ");
System.out.println(" 1. Insertion ");
System.out.println(" 2. View ");
System.out.println(" 3. Delete ");
System.out.println(" 4. Update ");
System.out.println(" 5. Exit ");
System.out.print("\n");
System.out.print("Please enter the choice what you want to perform in the database: ");
choice=Integer.parseInt(br.readLine());
switch(choice) {
case 1:{
System.out.print("Enter the username you want to insert data into the database: ");
String username=br.readLine();
System.out.print("Enter the password you want to insert data into the database: ");
String password=br.readLine();
try {
int i= jdbc.insert(username, password);
if (i>0) {
System.out.println((count++) + " Data has been inserted successfully");
}else{
System.out.println("Data has not been inserted ");
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}//End of case 1
break;
case 2:{
System.out.print("Enter the username : ");
String username=br.readLine();
try {
jdbc.view(username);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}//End of case 2
break;
case 3:{
System.out.print("Enter the userid, you want to delete: ");
int userid=Integer.parseInt(br.readLine());
try {
int i= jdbc.delete(userid);
if (i>0) {
System.out.println((count++) + " Data has been deleted successfully");
}else{
System.out.println("Data has not been deleted");
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}//End of case 3
break;
case 4:{
System.out.print("Enter the username, you want to update: ");
String username=br.readLine();
System.out.print("Enter the new password ");
String password=br.readLine();
try {
int i= jdbc.update(username, password);
if (i>0) {
System.out.println((count++) + " Data has been updated successfully");
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to continue...");
System.in.read();
}// end of case 4
break;
default:
return;
}
} while (choice!=4);
}
}
This pattern should be followed, if the cost of creating a new object is expensive and
resource intensive.
The clients can get new objects without knowing which type of object it will be.
When the client application needs to be unaware of object creation and representation.
File: Prototype.java
interface Prototype {
public Prototype getClone();
}//End of Prototype interface.
File: EmployeeRecord.java
class EmployeeRecord implements Prototype{
private int id;
private String name, designation;
private double salary;
private String address;
public EmployeeRecord(){
System.out.println(" Employee Records of Oracle Corporation ");
System.out.println("---------------------------------------------");
System.out.println("Eid"+"\t"+"Ename"+"\t"+"Edesignation"+"\t"+"Esalary"+"\t\t"+"Eaddre
}
public EmployeeRecord(int id, String name, String designation, double salary, String address)
this();
this.id = id;
this.name = name;
this.designation = designation;
this.salary = salary;
this.address = address;
}
public void showRecord(){
System.out.println(id+"\t"+name+"\t"+designation+"\t"+salary+"\t"+address);
}
@Override
public Prototype getClone() {
return new EmployeeRecord(id,name,designation,salary,address);
}
}//End of EmployeeRecord class.
File: PrototypeDemo.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class PrototypeDemo{
public static void main(String[] args) throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Employee Id: ");
int eid=Integer.parseInt(br.readLine());
System.out.print("\n");
System.out.print("Enter Employee Name: ");
String ename=br.readLine();
System.out.print("\n");
System.out.print("Enter Employee Designation: ");
String edesignation=br.readLine();
System.out.print("\n");
System.out.print("Enter Employee Address: ");
String eaddress=br.readLine();
System.out.print("\n");
System.out.print("Enter Employee Salary: ");
double esalary= Double.parseDouble(br.readLine());
System.out.print("\n");
EmployeeRecord e1=new EmployeeRecord(eid,ename,edesignation,esalary,eaddress);
e1.showRecord();
System.out.println("\n");
EmployeeRecord e2=(EmployeeRecord) e1.getClone();
e2.showRecord();
}
}//End of the ProtoypeDemo class.
Output
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Feedback
Home Core Java Servlet JSP Struts2 Mail API Hibernate Spring Android
Adapter Pattern
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.
It is used:
When you want to create a reusable class that cooperates with classes which don't have
compatible interfaces.
When you want to create a reusable class that cooperates with classes which don't have
compatible interfaces.
Let's understand the example of adapter design pattern by the above UML diagram.
Target Interface: This is the desired interface class which will be used by the clients.
Adapter class: This class is a wrapper class which implements the desired target
interface and modifies the specific request available from the Adaptee class.
Adaptee class: This is the class which is used by the Adapter class to reuse the existing
functionality and modify them for desired use.
Client: This class will interact with the Adapter class.
Step 1
public interface CreditCard {
public void giveBankDetails();
public String getCreditCard();
}// End of the CreditCard interface.
Step 2
File: BankDetails.java
// This is the adapter class.
public class BankDetails{
private String bankName;
private String accHolderName;
private long accNumber;
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getAccHolderName() {
return accHolderName;
}
public void setAccHolderName(String accHolderName) {
this.accHolderName = accHolderName;
}
public long getAccNumber() {
return accNumber;
}
public void setAccNumber(long accNumber) {
this.accNumber = accNumber;
}
}// End of the BankDetails class.
Step 3
File: BankCustomer.java
// This is the adapter class
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BankCustomer extends BankDetails implements CreditCard {
public void giveBankDetails(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the account holder name :");
String customername=br.readLine();
System.out.print("\n");
System.out.print("Enter the account number:");
long accno=Long.parseLong(br.readLine());
System.out.print("\n");
System.out.print("Enter the bank name :");
String bankname=br.readLine();
setAccHolderName(customername);
setAccNumber(accno);
setBankName(bankname);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public String getCreditCard() {
long accno=getAccNumber();
String accholdername=getAccHolderName();
String bname=getBankName();
return ("The Account number "+accno+" of "+accholdername+" in "+bname+ "
bank is valid and authenticated for issuing the credit card. ");
}
}//End of the BankCustomer class.
Step 4
File: AdapterPatternDemo.java
//This is the client class.
Bridge Pattern
A Bridge Pattern says that just "decouple the functional abstraction from the
implementation so that the two can vary independently".
When you don't want a permanent binding between the functional abstraction and its
implementation.
When both the functional abstraction and its implementation need to extended using
sub-classes.
It is mostly used in those places where changes are made in the implementation does
not affect the clients.
Step 1
Create a Question interface that provides the navigation from one question to another or
vice-versa.
// this is the Question interface.
public interface Question {
public void nextQuestion();
public void previousQuestion();
public void newQuestion(String q);
public void deleteQuestion(String q);
public void displayQuestion();
public void displayAllQuestions();
}
// End of the Question interface.
Step 2
// this is the JavaQuestions class.
import java.util.ArrayList;
import java.util.List;
public class JavaQuestions implements Question {
private List <String> questions = new ArrayList<String>();
private int current = 0;
public JavaQuestions(){
questions.add("What is class? ");
questions.add("What is interface? ");
questions.add("What is abstraction? ");
questions.add("How multiple polymorphism is achieved in java? ");
questions.add("How many types of exception handling are there in java? ");
questions.add("Define the keyword final for variable, method, and class in java? ");
questions.add("What is abstract class? ");
questions.add("What is multi-threading? ");
}
public void nextQuestion() {
if( current <= questions.size()-1 )
current++;
System.out.print(current);
}
public void previousQuestion() {
if( current > 0 )
current--;
}
public void newQuestion(String quest) {
questions.add(quest);
}
public void deleteQuestion(String quest) {
questions.remove(quest);
}
public void displayQuestion() {
System.out.println( questions.get(current) );
}
public void displayAllQuestions() {
for (String quest : questions) {
System.out.println(quest);
}
}
}// End of the JavaQuestions class.
Step 3
Create a QuestionManager class that will use Question interface which will act as a
bridge..
// this is the QuestionManager class.
public class QuestionManager {
protected Question q;
public String catalog;
public QuestionManager(String catalog) {
this.catalog=catalog;
}
public void next() {
q.nextQuestion();
}
public void previous() {
q.previousQuestion();
}
public void newOne(String quest) {
q.newQuestion(quest);
}
public void delete(String quest) {
q.deleteQuestion(quest);
}
public void display() {
q.displayQuestion();
}
public void displayAll() {
System.out.println("Question Paper: " + catalog);
q.displayAllQuestions();
}
}// End of the QuestionManager class.
Step 4
// this is the QuestionFormat class.
public class QuestionFormat extends QuestionManager {
public QuestionFormat(String catalog){
super(catalog);
}
public void displayAll() {
System.out.println("\n---------------------------------------------------------");
super.displayAll();
System.out.println("-----------------------------------------------------------");
}
}// End of the QuestionFormat class.
Step 5
// this is the BridgePatternDemo class.
public class BridgePatternDemo {
public static void main(String[] args) {
QuestionFormat questions = new QuestionFormat("Java Programming Language");
questions.q = new JavaQuestions();
questions.delete("what is class?");
questions.display();
questions.newOne("What is inheritance? ");
questions.newOne("How many types of inheritance are there in java?");
questions.displayAll();
}
}// End of the BridgePatternDemo class.
Output
What is interface?
--------------------------------------------------------------------
Question Paper: Java Programming Language
What is class?
What is interface?
What is abstraction?
How multiple polymorphism is achieved in java?
How many types of exception handling are there in java?
Define the keyword final for variable, method, and class in java?
What is abstract class?
What is multi-threading?
What is inheritance?
How many types of inheritance are there in java?
-----------------------------------------------------------------------
<<Prev
Next>>
Composite Pattern
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".
It is used:
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.
1) Component
Implements default behavior for the interface common to all classes as appropriate.
2) Leaf
3) Composite
4) Client
Client uses the component class interface to interact with objects in the composition
structure. If recipient is the leaf then request will be handled directly. If recipient is a
composite, then it usually forwards the request to its child for performing the additional
operations.
We can easily understand the example of composite design pattern by the UML diagram
given below:
Implementation of above UML:
Step 1
// this is the Employee interface i.e. Component.
public interface Employee {
public int getId();
public String getName();
public double getSalary();
public void print();
public void add(Employee employee);
public void remove(Employee employee);
public Employee getChild(int i);
}// End of the Employee interface.
Step 2
File: BankManager.java
// this is the BankManager class i.e. Composite.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BankManager implements Employee {
private int id;
private String name;
private double salary;
public BankManager(int id,String name,double salary) {
this.id=id;
this.name = name;
this.salary = salary;
}
List<Employee> employees = new ArrayList<Employee>();
@Override
public void add(Employee employee) {
employees.add(employee);
}
@Override
public Employee getChild(int i) {
return employees.get(i);
}
@Override
public void remove(Employee employee) {
employees.remove(employee);
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public double getSalary() {
return salary;
}
@Override
public void print() {
System.out.println("==========================");
System.out.println("Id ="+getId());
System.out.println("Name ="+getName());
System.out.println("Salary ="+getSalary());
System.out.println("==========================");
Iterator<Employee> it = employees.iterator();
while(it.hasNext()) {
Employee employee = it.next();
employee.print();
}
}
}// 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
public class Cashier implements Employee{
/*
In this class,there are many methods which are not applicable to cashier because
it is a leaf node.
*/
private int id;
private String name;
private double salary;
public Cashier(int id,String name,double salary) {
this.id=id;
this.name = name;
this.salary = salary;
}
@Override
public void add(Employee employee) {
//this is leaf node so this method is not applicable to this class.
}
@Override
public Employee getChild(int i) {
//this is leaf node so this method is not applicable to this class.
return null;
}
@Override
public int getId() {
// TODO Auto-generated method stub
return id;
}
@Override
public String getName() {
return name;
}
@Override
public double getSalary() {
return salary;
}
@Override
public void print() {
System.out.println("==========================");
System.out.println("Id ="+getId());
System.out.println("Name ="+getName());
System.out.println("Salary ="+getSalary());
System.out.println("==========================");
}
@Override
public void remove(Employee employee) {
//this is leaf node so this method is not applicable to this class.
}
}
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
public class Accountant implements Employee{
/*
In this class,there are many methods which are not applicable to cashier because
it is a leaf node.
*/
private int id;
private String name;
private double salary;
public Accountant(int id,String name,double salary) {
this.id=id;
this.name = name;
this.salary = salary;
}
@Override
public void add(Employee employee) {
//this is leaf node so this method is not applicable to this class.
}
@Override
public Employee getChild(int i) {
//this is leaf node so this method is not applicable to this class.
return null;
}
@Override
public int getId() {
// TODO Auto-generated method stub
return id;
}
@Override
public String getName() {
return name;
}
@Override
public double getSalary() {
return salary;
}
@Override
public void print() {
System.out.println("=========================");
System.out.println("Id ="+getId());
System.out.println("Name ="+getName());
System.out.println("Salary ="+getSalary());
System.out.println("=========================");
}
@Override
public void remove(Employee employee) {
//this is leaf node so this method is not applicable to this class.
}
}
Step 5
Create a CompositePatternDemo class that will also be treated as a Client and ii will use
the Employee interface.
File: CompositePatternDemo.java
public class CompositePatternDemo {
public static void main(String args[]){
Employee emp1=new Cashier(101,"Sohan Kumar", 20000.0);
Employee emp2=new Cashier(102,"Mohan Kumar", 25000.0);
Employee emp3=new Accountant(103,"Seema Mahiwal", 30000.0);
Employee manager1=new BankManager(100,"Ashwani Rajput",100000.0);
manager1.add(emp1);
manager1.add(emp2);
manager1.add(emp3);
manager1.print();
}
}
Output
==========================
Id =100
Name =Ashwani Rajput
Salary =100000.0
==========================
==========================
Id =101
Name =Sohan Kumar
Salary =20000.0
==========================
==========================
Id =102
Name =Mohan Kumar
Salary =25000.0
==========================
=========================
Id =103
Name =Seema Mahiwal
Decorator Pattern
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.
It is used:
When you want to transparently and dynamically add responsibilities to objects without
affecting other objects.
When you want to add responsibilities to an object that you may want to change in
future.
public interface Food {
public String prepareFood();
public double foodPrice();
}// 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
public class VegFood implements Food {
public String prepareFood(){
return "Veg Food";
}
public double foodPrice(){
return 50.0;
}
}
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
public abstract class FoodDecorator implements Food{
private Food newFood;
public FoodDecorator(Food newFood) {
this.newFood=newFood;
}
@Override
public String prepareFood(){
return newFood.prepareFood();
}
public double foodPrice(){
return newFood.foodPrice();
}
}
Step 4:Create a NonVegFood concrete class that will extend the FoodDecorator class and
override it's all methods.
File: NonVegFood.java
public class NonVegFood extends FoodDecorator{
public NonVegFood(Food newFood) {
super(newFood);
}
public String prepareFood(){
return super.prepareFood() +" With Roasted Chiken and Chiken Curry ";
}
public double foodPrice() {
return super.foodPrice()+150.0;
}
}
Step 5:Create a ChineeseFood concrete class that will extend the FoodDecorator class and
override it's all methods.
File: ChineeseFood.java
public class ChineeseFood extends FoodDecorator{
public ChineeseFood(Food newFood) {
super(newFood);
}
public String prepareFood(){
return super.prepareFood() +" With Fried Rice and Manchurian ";
}
public double foodPrice() {
return super.foodPrice()+65.0;
}
}
Step 6:Create a DecoratorPatternCustomer class that will use Food interface to use which
type of food customer wants means (Decorates).
File: DecoratorPatternCustomer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DecoratorPatternCustomer {
private static int choice;
public static void main(String args[]) throws NumberFormatException, IOException {
do{
System.out.print("========= Food Menu ============ \n");
System.out.print(" 1. Vegetarian Food. \n");
System.out.print(" 2. Non-Vegetarian Food.\n");
System.out.print(" 3. Chineese Food. \n");
System.out.print(" 4. Exit \n");
System.out.print("Enter your choice: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
choice=Integer.parseInt(br.readLine());
switch (choice) {
case 1:{
VegFood vf=new VegFood();
System.out.println(vf.prepareFood());
System.out.println( vf.foodPrice());
}
break;
case 2:{
Food f1=new NonVegFood((Food) new VegFood());
System.out.println(f1.prepareFood());
System.out.println( f1.foodPrice());
}
break;
case 3:{
Food f2=new ChineeseFood((Food) new VegFood());
System.out.println(f2.prepareFood());
System.out.println( f2.foodPrice());
}
break;
default:{
System.out.println("Other than these no food available");
}
return;
}//end of switch
}while(choice!=4);
}
}
Output
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 1
Veg Food
50.0
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 2
Veg Food With Roasted Chiken and Chiken Curry
200.0
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 3
Veg Food With Fried Rice and Manchurian
115.0
========= Food Menu ============
1. Vegetarian Food.
2. Non-Vegetarian Food.
3. Chineese Food.
4. Exit
Enter your choice: 4
Other than these no food available
← Prev
Next →
Home Core Java Servlet JSP Struts2 Mail API Hibernate Spring Android
Flyweight Pattern
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".
← Prev
Next →
For Videos Join Our Youtube Channel: Join Now
Feedback
⇧ SCROLL TO TOP
Help Others, Please Share
Proxy Pattern
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.
RMI API uses proxy design pattern. Stub and Skeleton are two proxy objects used in
RMI.
It provides the protection to the original object from the outside world.
It is used:
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.
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.
Let's understand the example of proxy design pattern by the above UML diagram.
Step 1
public interface OfficeInternetAccess {
public void grantInternetAccess();
}
Step 2
File: RealInternetAccess.java
public class RealInternetAccess implements OfficeInternetAccess {
private String employeeName;
public RealInternetAccess(String empName) {
this.employeeName = empName;
}
@Override
public void grantInternetAccess() {
System.out.println("Internet Access granted for employee: "+ employeeName);
}
}
Step 3
File: ProxyInternetAccess.java
public class ProxyInternetAccess implements OfficeInternetAccess {
private String employeeName;
private RealInternetAccess realaccess;
public ProxyInternetAccess(String employeeName) {
this.employeeName = employeeName;
}
@Override
public void grantInternetAccess()
{
if (getRole(employeeName) > 4)
{
realaccess = new RealInternetAccess(employeeName);
realaccess.grantInternetAccess();
}
else
{
System.out.println("No Internet access granted. Your job level is below 5");
}
}
public int getRole(String emplName) {
// Check role from the database based on Name and designation
// return job level or job designation.
return 9;
}
}
Step 4
Now, Create a ProxyPatternClient class that can access the internet actually.
File: ProxyPatternClient.java
public class ProxyPatternClient {
public static void main(String[] args)
{
OfficeInternetAccess access = new ProxyInternetAccess("Ashwani Rajput");
access.grantInternetAccess();
}
}
Output
No Internet access granted. Your job level is below 5
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Home Core Java Servlet JSP Struts2 Mail API Hibernate Spring Android
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.
<<Prev
Next>>
For Videos Join Our Youtube Channel: Join Now
Feedback
Chain Of Responsibility Pattern
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.
It is used:
When more than one object can handle a request and the handler is unknown.
When the group of objects that can handle the request must be specified in dynamic
way.
Let's understand the example of Chain of Responsibility Pattern by the above UML
diagram.
Step 1
public abstract class Logger {
public static int OUTPUTINFO=1;
public static int ERRORINFO=2;
public static int DEBUGINFO=3;
protected int levels;
protected Logger nextLevelLogger;
public void setNextLevelLogger(Logger nextLevelLogger) {
this.nextLevelLogger = nextLevelLogger;
}
public void logMessage(int levels, String msg){
if(this.levels<=levels){
displayLogInfo(msg);
}
if (nextLevelLogger!=null) {
nextLevelLogger.logMessage(levels, msg);
}
}
protected abstract void displayLogInfo(String msg);
}
Step 2
File: ConsoleBasedLogger.java
public class ConsoleBasedLogger extends Logger {
public ConsoleBasedLogger(int levels) {
this.levels=levels;
}
@Override
protected void displayLogInfo(String msg) {
System.out.println("CONSOLE LOGGER INFO: "+msg);
}
}
Step 3
File: DebugBasedLogger.java
public class DebugBasedLogger extends Logger {
public DebugBasedLogger(int levels) {
this.levels=levels;
}
@Override
protected void displayLogInfo(String msg) {
System.out.println("DEBUG LOGGER INFO: "+msg);
}
}// End of the DebugBasedLogger class.
Step 4
Create a ErrorBasedLogger class.
File: ErrorBasedLogger.java
public class ErrorBasedLogger extends Logger {
public ErrorBasedLogger(int levels) {
this.levels=levels;
}
@Override
protected void displayLogInfo(String msg) {
System.out.println("ERROR LOGGER INFO: "+msg);
}
}// End of the ErrorBasedLogger class.
Step 5
File: ChainofResponsibilityClient.java
public class ChainofResponsibilityClient {
private static Logger doChaining(){
Logger consoleLogger = new ConsoleBasedLogger(Logger.OUTPUTINFO);
Logger errorLogger = new ErrorBasedLogger(Logger.ERRORINFO);
consoleLogger.setNextLevelLogger(errorLogger);
Logger debugLogger = new DebugBasedLogger(Logger.DEBUGINFO);
errorLogger.setNextLevelLogger(debugLogger);
return consoleLogger;
}
public static void main(String args[]){
Logger chainLogger= doChaining();
chainLogger.logMessage(Logger.OUTPUTINFO, "Enter the sequence of values ");
chainLogger.logMessage(Logger.ERRORINFO, "An error is occured now");
chainLogger.logMessage(Logger.DEBUGINFO, "This was the error now debugging is co
}
}
Output
bilityClient
CONSOLE LOGGER INFO: Enter the sequence of values
CONSOLE LOGGER INFO: An error is occured now
ERROR LOGGER INFO: An error is occured now
CONSOLE LOGGER INFO: This was the error now debugging is compeled
ERROR LOGGER INFO: This was the error now debugging is compeled
DEBUG LOGGER INFO: This was the error now debugging is compeled
← Prev
Next →
For Videos Join Our Youtube Channel: Join Now
Feedback
It separates the object that invokes the operation from the object that actually performs
the operation.
It makes easy to add new commands, because existing classes remain unchanged.
It is used:
Let's understand the example of adapter design pattern by the above UML diagram.
ConcreteCommand This class extends the Command interface and implements the
execute method. This class creates a binding between the action and the receiver.
Client This class creates the ConcreteCommand class and associates it with the receiver.
Invoker This class asks the command to carry out the request.
Receiver This class knows to perform the operation.
Step 1
public interface ActionListenerCommand {
public void execute();
}
Step 2
File: Document.java
public class Document {
public void open(){
System.out.println("Document Opened");
}
public void save(){
System.out.println("Document Saved");
}
}
Step 3
File: ActionOpen.java
public class ActionOpen implements ActionListenerCommand{
private Document doc;
public ActionOpen(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.open();
}
}
Step 4
File: AdapterPatternDemo.java
public class ActionSave implements ActionListenerCommand{
private Document doc;
public ActionSave(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.save();
}
}
Step 5
File: ActionSave.java
public class ActionSave implements ActionListenerCommand{
private Document doc;
public ActionSave(Document doc) {
this.doc = doc;
}
@Override
public void execute() {
doc.save();
}
}
Step 6
File: AdapterPatternDemo.java
public class CommandPatternClient {
public static void main(String[] args) {
Document doc = new Document();
ActionListenerCommand clickOpen = new ActionOpen(doc);
ActionListenerCommand clickSave = new ActionSave(doc);
MenuOptions menu = new MenuOptions(clickOpen, clickSave);
menu.clickOpen();
menu.clickSave();
}
}
download this example
Output
Document Opened
Document Saved
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Feedback
Basically the Interpreter pattern has limited area where it can be applied. We can
discuss the Interpreter pattern only in terms of formal grammars but in this area
there are better solutions that is why it is not frequently used.
This pattern can applied for parsing the expressions defined in simple grammars
and sometimes in simple rule engines.
It is used:
Let's understand the example of Interpreter Pattern by the above UML diagram.
Step 1
public interface Pattern {
public String conversion(String exp);
}
Step 2
Create a InfixToPostfixPattern class that will allow what kind of pattern you want
to convert.
File: InfixToPostfixPattern.java
import java.util.Stack;
public class InfixToPostfixPattern implements Pattern{
@Override
public String conversion(String exp) {
int priority = 0;// for the priority of operators.
String postfix = "";
Stack<Character> s1 = new Stack<Character>();
for (int i = 0; i < exp.length(); i++)
{
char ch = exp.charAt(i);
if (ch == '+' || ch == '-' || ch == '*' || ch == '/'||ch=='%')
{
// check the precedence
if (s1.size() <= 0)
s1.push(ch);
}
else
{
Character chTop = (Character) s1.peek();
if (chTop == '*' || chTop == '/')
priority = 1;
else
priority = 0;
if (priority == 1)
{
if (ch == '*' || ch == '/'||ch=='%')
{
postfix += s1.pop();
i--;
}
else
{ // Same
postfix += s1.pop();
i--;
}
}
else
{
if (ch == '+' || ch == '-')
{
postfix += s1.pop();
s1.push(ch);
}
else
s1.push(ch);
}
}
}
else
{
postfix += ch;
}
}
int len = s1.size();
for (int j = 0; j < len; j++)
postfix += s1.pop();
return postfix;
}
}// End of the InfixToPostfixPattern class.
Step 3
File: InterpreterPatternClient.java
public class InterpreterPatternClient {
public static void main(String[] args)
{
String infix = "a+b*c";
InfixToPostfixPattern ip=new InfixToPostfixPattern();
String postfix = ip.conversion(infix);
System.out.println("Infix: " + infix);
System.out.println("Postfix: " + postfix);
}
}
Output
Infix: a+b*c
Postfix: abc*+
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Feedback
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.
Benefits:
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:
Step 1:
//This is an interface.
public interface ApnaChatRoom {
public void showMsg(String msg, Participant p);
}// 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.
//This is a class.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ApnaChatRoomImpl implements ApnaChatRoom{
//get current date time
DateFormat dateFormat = new SimpleDateFormat("E dd-MM-yyyy hh:mm a");
Date date = new Date();
@Override
public void showMsg(String msg, Participant p) {
System.out.println(p.getName()+"'gets message: "+msg);
System.out.println("\t\t\t\t"+"["+dateFormat.format(date).toString()+"]");
}
}// End of the ApnaChatRoomImpl class.
Step 3:
//This is an abstract class.
public abstract class Participant {
public abstract void sendMsg(String msg);
public abstract void setname(String name);
public abstract String getName();
}// End of the Participant abstract class.
Step 4:
Create a User1 class that will extend Participant abstract class and will use the
ApnaChatRoom interface.
//This is a class.
public class User1 extends Participant {
private String name;
private ApnaChatRoom chat;
@Override
public void sendMsg(String msg) {
chat.showMsg(msg,this);
}
@Override
public void setname(String name) {
this.name=name;
}
@Override
public String getName() {
return name;
}
public User1(ApnaChatRoom chat){
this.chat=chat;
}
}// End of the User1 class.
Step 5:
Create a User2 class that will extend Participant abstract class and will use the
ApnaChatRoom interface.
//This is a class.
public class User2 extends Participant {
private String name;
private ApnaChatRoom chat;
@Override
public void sendMsg(String msg) {
this.chat.showMsg(msg,this);
}
@Override
public void setname(String name) {
this.name=name;
}
@Override
public String getName() {
return name;
}
public User2(ApnaChatRoom chat){
this.chat=chat;
}
}
// End of the User2 class.
Step 6:
//This is a class.
public class MediatorPatternDemo {
public static void main(String args[])
{
ApnaChatRoom chat = new ApnaChatRoomImpl();
User1 u1=new User1(chat);
u1.setname("Ashwani Rajput");
u1.sendMsg("Hi Ashwani! how are you?");
User2 u2=new User2(chat);
u2.setname("Soono Jaiswal");
u2.sendMsg("I am Fine ! You tell?");
}
}// End of the MediatorPatternDemo class.
Output:
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Feedback
Template Pattern
A Template Pattern says that "just define the skeleton of a function in an operation,
deferring some steps to its subclasses".
Benefits:
It is very common technique for reusing the code.This is only the main benefit of it.
Usage:
It is used when the common behavior among sub-classes should be moved to a single
common class by avoiding the duplication.
Step 1:
//This is an abstract class.
public abstract class Game {
abstract void initialize();
abstract void start();
abstract void end();
public final void play(){
//initialize the game
initialize();
//start game
start();
//end game
end();
}
}// 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.
//This is a class.
public class Chess extends Game {
@Override
void initialize() {
System.out.println("Chess Game Initialized! Start playing.");
}
@Override
void start() {
System.out.println("Game Started. Welcome to in the chess game!");
}
@Override
void end() {
System.out.println("Game Finished!");
}
}// End of the Chess class.
Step 3:
Create a Soccer class that will extend Game abstract class for giving the definition to its
method.
//This is a class.
public class Soccer extends Game {
@Override
void initialize() {
System.out.println("Soccer Game Initialized! Start playing.");
}
@Override
void start() {
System.out.println("Game Started. Welcome to in the Soccer game!");
}
@Override
void end() {
System.out.println("Game Finished!");
}
}// End of the Soccer class.
Step 4:
//This is a class.
public class TemplatePatternDemo {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, Cl
Class c=Class.forName(args[0]);
Game game=(Game) c.newInstance();
game.play();
}
}// End of the Soccer class.
Output:
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now