Category: 03. Design Patterns

https://cdn-icons-png.freepik.com/512/8361/8361102.png

  • Transfer Object Pattern

    The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. It does not have any behavior. Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values in database in one shot. Following are the entities of this type of design pattern.

    • Business Object – Business Service fills the Transfer Object with data.
    • Transfer Object – Simple POJO having methods to set/get attributes only.
    • Client – Client either requests or sends the Transfer Object to Business Object.

    Implementation

    We are going to create a StudentBO as Business Object,Student as Transfer Object representing our entities.

    TransferObjectPatternDemo, our demo class, is acting as a client here and will use StudentBO and Student to demonstrate Transfer Object Design Pattern.

    Transfer Object Pattern UML Diagram

    Step 1

    Create Transfer Object.

    StudentVO.java

    public class StudentVO {
       private String name;
       private int rollNo;
    
       StudentVO(String name, int rollNo){
    
      this.name = name;
      this.rollNo = rollNo;
    } public String getName() {
      return name;
    } public void setName(String name) {
      this.name = name;
    } public int getRollNo() {
      return rollNo;
    } public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create Business Object.

    StudentBO.java

    import java.util.ArrayList;
    import java.util.List;
    
    public class StudentBO {
    	
       //list is working as a database
       List<StudentVO> students;
    
       public StudentBO(){
    
      students = new ArrayList&lt;StudentVO&gt;();
      StudentVO student1 = new StudentVO("Robert",0);
      StudentVO student2 = new StudentVO("John",1);
      students.add(student1);
      students.add(student2);		
    } public void deleteStudent(StudentVO student) {
      students.remove(student.getRollNo());
      System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database");
    } //retrive list of students from the database public List<StudentVO> getAllStudents() {
      return students;
    } public StudentVO getStudent(int rollNo) {
      return students.get(rollNo);
    } public void updateStudent(StudentVO student) {
      students.get(student.getRollNo()).setName(student.getName());
      System.out.println("Student: Roll No " + student.getRollNo() +", updated in the database");
    } }

    Step 3

    Use the StudentBO to demonstrate Transfer Object Design Pattern.

    TransferObjectPatternDemo.java

    public class TransferObjectPatternDemo {
       public static void main(String[] args) {
    
      StudentBO studentBusinessObject = new StudentBO();
      //print all students
      for (StudentVO student : studentBusinessObject.getAllStudents()) {
         System.out.println("Student: &#91;RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
      }
      //update student
      StudentVO student = studentBusinessObject.getAllStudents().get(0);
      student.setName("Michael");
      studentBusinessObject.updateStudent(student);
      //get the student
      student = studentBusinessObject.getStudent(0);
      System.out.println("Student: &#91;RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
    } }

    Step 4

    Verify the output.

    Student: [RollNo : 0, Name : Robert ]
    Student: [RollNo : 1, Name : John ]
    Student: Roll No 0, updated in the database
    Student: [RollNo : 0, Name : Michael ]
    
  • Service Locator Pattern

    The service locator design pattern is used when we want to locate various services using JNDI lookup. Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent. Following are the entities of this type of design pattern.

    • Service – Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server.
    • Context / Initial Context – JNDI Context carries the reference to service used for lookup purpose.
    • Service Locator – Service Locator is a single point of contact to get services by JNDI lookup caching the services.
    • Cache – Cache to store references of services to reuse them
    • Client – Client is the object that invokes the services via ServiceLocator.

    Implementation

    We are going to create a ServiceLocator,InitialContextCacheService as various objects representing our entities.Service1 and Service2 represent concrete services.

    ServiceLocatorPatternDemo, our demo class, is acting as a client here and will use ServiceLocator to demonstrate Service Locator Design Pattern.

    Service Locator Pattern UML Diagram

    Step 1

    Create Service interface.

    Service.java

    public interface Service {
       public String getName();
       public void execute();
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete services.

    Service1.java

    public class Service1 implements Service {
       public void execute(){
    
      System.out.println("Executing Service1");
    } @Override public String getName() {
      return "Service1";
    } }

    Service2.java

    public class Service2 implements Service {
       public void execute(){
    
      System.out.println("Executing Service2");
    } @Override public String getName() {
      return "Service2";
    } }

    Step 3

    Create InitialContext for JNDI lookup

    InitialContext.java

    public class InitialContext {
       public Object lookup(String jndiName){
       
    
      if(jndiName.equalsIgnoreCase("SERVICE1")){
         System.out.println("Looking up and creating a new Service1 object");
         return new Service1();
      }
      else if (jndiName.equalsIgnoreCase("SERVICE2")){
         System.out.println("Looking up and creating a new Service2 object");
         return new Service2();
      }
      return null;		
    } }

    Step 4

    Create Cache

    Cache.java

    import java.util.ArrayList;
    import java.util.List;
    
    public class Cache {
    
       private List<Service> services;
    
       public Cache(){
    
      services = new ArrayList&lt;Service&gt;();
    } public Service getService(String serviceName){
      for (Service service : services) {
         if(service.getName().equalsIgnoreCase(serviceName)){
            System.out.println("Returning cached  " + serviceName + " object");
            return service;
         }
      }
      return null;
    } public void addService(Service newService){
      boolean exists = false;
      
      for (Service service : services) {
         if(service.getName().equalsIgnoreCase(newService.getName())){
            exists = true;
         }
      }
      if(!exists){
         services.add(newService);
      }
    } }

    Step 5

    Create Service Locator

    ServiceLocator.java

    public class ServiceLocator {
       private static Cache cache;
    
       static {
    
      cache = new Cache();		
    } public static Service getService(String jndiName){
      Service service = cache.getService(jndiName);
      if(service != null){
         return service;
      }
      InitialContext context = new InitialContext();
      Service service1 = (Service)context.lookup(jndiName);
      cache.addService(service1);
      return service1;
    } }

    Step 6

    Use the ServiceLocator to demonstrate Service Locator Design Pattern.

    ServiceLocatorPatternDemo.java

    public class ServiceLocatorPatternDemo {
       public static void main(String[] args) {
    
      Service service = ServiceLocator.getService("Service1");
      service.execute();
      service = ServiceLocator.getService("Service2");
      service.execute();
      service = ServiceLocator.getService("Service1");
      service.execute();
      service = ServiceLocator.getService("Service2");
      service.execute();		
    } }

    Step 7

    Verify the output.

    Looking up and creating a new Service1 object
    Executing Service1
    Looking up and creating a new Service2 object
    Executing Service2
    Returning cached  Service1 object
    Executing Service1
    Returning cached  Service2 object
    Executing Service2
    
  • Intercepting Filter Pattern

    The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. Filters are defined and applied on the request before passing the request to actual target application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern.

    • Filter – Filter which will performs certain task prior or after execution of request by request handler.
    • Filter Chain – Filter Chain carries multiple filters and help to execute them in defined order on target.
    • Target – Target object is the request handler
    • Filter Manager – Filter Manager manages the filters and Filter Chain.
    • Client – Client is the object who sends request to the Target object.

    Implementation

    We are going to create a FilterChain,FilterManagerTargetClient as various objects representing our entities.AuthenticationFilter and DebugFilter represent concrete filters.

    InterceptingFilterDemo, our demo class, will use Client to demonstrate Intercepting Filter Design Pattern.

    Intercepting Filter Pattern UML Diagram

    Step 1

    Create Filter interface.

    Filter.java

    public interface Filter {
       public void execute(String request);
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete filters.

    AuthenticationFilter.java

    public class AuthenticationFilter implements Filter {
       public void execute(String request){
    
      System.out.println("Authenticating request: " + request);
    } }

    DebugFilter.java

    public class DebugFilter implements Filter {
       public void execute(String request){
    
      System.out.println("request log: " + request);
    } }

    Step 3

    Create Target

    Target.java

    public class Target {
       public void execute(String request){
    
      System.out.println("Executing request: " + request);
    } }

    Step 4

    Create Filter Chain

    FilterChain.java

    import java.util.ArrayList;
    import java.util.List;
    
    public class FilterChain {
       private List<Filter> filters = new ArrayList<Filter>();
       private Target target;
    
       public void addFilter(Filter filter){
    
      filters.add(filter);
    } public void execute(String request){
      for (Filter filter : filters) {
         filter.execute(request);
      }
      target.execute(request);
    } public void setTarget(Target target){
      this.target = target;
    } }

    Step 5

    Create Filter Manager

    FilterManager.java

    public class FilterManager {
       FilterChain filterChain;
    
       public FilterManager(Target target){
    
      filterChain = new FilterChain();
      filterChain.setTarget(target);
    } public void setFilter(Filter filter){
      filterChain.addFilter(filter);
    } public void filterRequest(String request){
      filterChain.execute(request);
    } }

    Step 6

    Create Client

    Client.java

    public class Client {
       FilterManager filterManager;
    
       public void setFilterManager(FilterManager filterManager){
    
      this.filterManager = filterManager;
    } public void sendRequest(String request){
      filterManager.filterRequest(request);
    } }

    Step 7

    Use the Client to demonstrate Intercepting Filter Design Pattern.

    InterceptingFilterDemo.java

    public class InterceptingFilterDemo {
       public static void main(String[] args) {
    
      FilterManager filterManager = new FilterManager(new Target());
      filterManager.setFilter(new AuthenticationFilter());
      filterManager.setFilter(new DebugFilter());
      Client client = new Client();
      client.setFilterManager(filterManager);
      client.sendRequest("HOME");
    } }

    Step 8

    Verify the output.

    Authenticating request: HOME
    request log: HOME
    Executing request: HOME
    
  • Front Controller Pattern

    The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern.

    • Front Controller – Single handler for all kinds of requests coming to the application (either web based/ desktop based).
    • Dispatcher – Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler.
    • View – Views are the object for which the requests are made.

    Implementation

    We are going to create a FrontController and Dispatcher to act as Front Controller and Dispatcher correspondingly. HomeView and StudentView represent various views for which requests can come to front controller.

    FrontControllerPatternDemo, our demo class, will use FrontController to demonstrate Front Controller Design Pattern.

    Front Controller Pattern UML Diagram

    Step 1

    Create Views.

    HomeView.java

    public class HomeView {
       public void show(){
    
      System.out.println("Displaying Home Page");
    } }

    StudentView.java

    public class StudentView {
       public void show(){
    
      System.out.println("Displaying Student Page");
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create Dispatcher.

    Dispatcher.java

    public class Dispatcher {
       private StudentView studentView;
       private HomeView homeView;
       
       public Dispatcher(){
    
      studentView = new StudentView();
      homeView = new HomeView();
    } public void dispatch(String request){
      if(request.equalsIgnoreCase("STUDENT")){
         studentView.show();
      }
      else{
         homeView.show();
      }	
    } }

    Step 3

    Create FrontController

    FrontController.java

    public class FrontController {
    	
       private Dispatcher dispatcher;
    
       public FrontController(){
    
      dispatcher = new Dispatcher();
    } private boolean isAuthenticUser(){
      System.out.println("User is authenticated successfully.");
      return true;
    } private void trackRequest(String request){
      System.out.println("Page requested: " + request);
    } public void dispatchRequest(String request){
      //log each request
      trackRequest(request);
      
      //authenticate the user
      if(isAuthenticUser()){
         dispatcher.dispatch(request);
      }	
    } }

    Step 4

    Use the FrontController to demonstrate Front Controller Design Pattern.

    FrontControllerPatternDemo.java

    public class FrontControllerPatternDemo {
       public static void main(String[] args) {
       
    
      FrontController frontController = new FrontController();
      frontController.dispatchRequest("HOME");
      frontController.dispatchRequest("STUDENT");
    } }

    Step 5

    Verify the output.

    Page requested: HOME
    User is authenticated successfully.
    Displaying Home Page
    Page requested: STUDENT
    User is authenticated successfully.
    Displaying Student Page
    
  • Data Access Object Pattern

    Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern.

    • Data Access Object Interface – This interface defines the standard operations to be performed on a model object(s).
    • Data Access Object concrete class – This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism.
    • Model Object or Value Object – This object is simple POJO containing get/set methods to store data retrieved using DAO class.

    Implementation

    We are going to create a Student object acting as a Model or Value Object.StudentDao is Data Access Object Interface.StudentDaoImpl is concrete class implementing Data Access Object Interface. DaoPatternDemo, our demo class, will use StudentDao to demonstrate the use of Data Access Object pattern.

    Data Access Object Pattern UML Diagram

    Step 1

    Create Value Object.

    Student.java

    public class Student {
       private String name;
       private int rollNo;
    
       Student(String name, int rollNo){
    
      this.name = name;
      this.rollNo = rollNo;
    } public String getName() {
      return name;
    } public void setName(String name) {
      this.name = name;
    } public int getRollNo() {
      return rollNo;
    } public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create Data Access Object Interface.

    StudentDao.java

    import java.util.List;
    
    public interface StudentDao {
       public List<Student> getAllStudents();
       public Student getStudent(int rollNo);
       public void updateStudent(Student student);
       public void deleteStudent(Student student);
    }
    

    Step 3

    Create concrete class implementing above interface.

    StudentDaoImpl.java

    import java.util.ArrayList;
    import java.util.List;
    
    public class StudentDaoImpl implements StudentDao {
    	
       //list is working as a database
       List<Student> students;
    
       public StudentDaoImpl(){
    
      students = new ArrayList&lt;Student&gt;();
      Student student1 = new Student("Robert",0);
      Student student2 = new Student("John",1);
      students.add(student1);
      students.add(student2);		
    } @Override public void deleteStudent(Student student) {
      students.remove(student.getRollNo());
      System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database");
    } //retrive list of students from the database @Override public List<Student> getAllStudents() {
      return students;
    } @Override public Student getStudent(int rollNo) {
      return students.get(rollNo);
    } @Override public void updateStudent(Student student) {
      students.get(student.getRollNo()).setName(student.getName());
      System.out.println("Student: Roll No " + student.getRollNo() + ", updated in the database");
    } }

    Step 4

    Use the StudentDao to demonstrate Data Access Object pattern usage.

    DaoPatternDemo.java

    public class DaoPatternDemo {
       public static void main(String[] args) {
    
      StudentDao studentDao = new StudentDaoImpl();
      //print all students
      for (Student student : studentDao.getAllStudents()) {
         System.out.println("Student: &#91;RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
      }
      //update student
      Student student =studentDao.getAllStudents().get(0);
      student.setName("Michael");
      studentDao.updateStudent(student);
      //get the student
      studentDao.getStudent(0);
      System.out.println("Student: &#91;RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");		
    } }

    Step 5

    Verify the output.

    Student: [RollNo : 0, Name : Robert ]
    Student: [RollNo : 1, Name : John ]
    Student: Roll No 0, updated in the database
    Student: [RollNo : 0, Name : Michael ]
    
  • Composite Entity Pattern

    Composite Entity pattern is used in EJB persistence mechanism. A Composite entity is an EJB entity bean which represents a graph of objects. When a composite entity is updated, internally dependent objects beans get updated automatically as being managed by EJB entity bean. Following are the participants in Composite Entity Bean.

    • Composite Entity – It is primary entity bean. It can be coarse grained or can contain a coarse grained object to be used for persistence purpose.
    • Coarse-Grained Object – This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects.
    • Dependent Object – Dependent object is an object which depends on coarse grained object for its persistence lifecycle.
    • Strategies – Strategies represents how to implement a Composite Entity.

    Implementation

    We are going to create CompositeEntity object acting as CompositeEntity. CoarseGrainedObject will be a class which contains dependent objects. CompositeEntityPatternDemo, our demo class will use Client class to demonstrate use of Composite Entity pattern.

    Composite Entity Pattern UML Diagram

    Step 1

    Create Dependent Objects.

    DependentObject1.java

    public class DependentObject1 {
    	
       private String data;
    
       public void setData(String data){
    
      this.data = data; 
    } public String getData(){
      return data;
    } }

    DependentObject2.java

    public class DependentObject2 {
    	
       private String data;
    
       public void setData(String data){
    
      this.data = data; 
    } public String getData(){
      return data;
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create Coarse Grained Object.

    CoarseGrainedObject.java

    public class CoarseGrainedObject {
       DependentObject1 do1 = new DependentObject1();
       DependentObject2 do2 = new DependentObject2();
    
       public void setData(String data1, String data2){
    
      do1.setData(data1);
      do2.setData(data2);
    } public String[] getData(){
      return new String&#91;] {do1.getData(),do2.getData()};
    } }

    Step 3

    Create Composite Entity.

    CompositeEntity.java

    public class CompositeEntity {
       private CoarseGrainedObject cgo = new CoarseGrainedObject();
    
       public void setData(String data1, String data2){
    
      cgo.setData(data1, data2);
    } public String[] getData(){
      return cgo.getData();
    } }

    Step 4

    Create Client class to use Composite Entity.

    Client.java

    public class Client {
       private CompositeEntity compositeEntity = new CompositeEntity();
    
       public void printData(){
       
    
      for (int i = 0; i &lt; compositeEntity.getData().length; i++) {
         System.out.println("Data: " + compositeEntity.getData()&#91;i]);
      }
    } public void setData(String data1, String data2){
      compositeEntity.setData(data1, data2);
    } }

    Step 5

    Use the Client to demonstrate Composite Entity design pattern usage.

    CompositeEntityPatternDemo.java

    public class CompositeEntityPatternDemo {
       public static void main(String[] args) {
       
    
       Client client = new Client();
       client.setData("Test", "Data");
       client.printData();
       client.setData("Second Test", "Data1");
       client.printData();
    } }

    Step 6

    Verify the output.

    Data: Test
    Data: Data
    Data: Second Test
    Data: Data1
    
  • Business Delegate Pattern

    Business Delegate Pattern is used to decouple presentation tier and business tier. It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code. In business tier we have following entities.

    • Client – Presentation tier code may be JSP, servlet or UI java code.
    • Business Delegate – A single entry point class for client entities to provide access to Business Service methods.
    • LookUp Service – Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object.
    • Business Service – Business Service interface. Concrete classes implement this business service to provide actual business implementation logic.

    Implementation

    We are going to create a ClientBusinessDelegateBusinessServiceLookUpServiceJMSService and EJBService representing various entities of Business Delegate patterns.

    BusinessDelegatePatternDemo, our demo class, will use BusinessDelegate and Client to demonstrate use of Business Delegate pattern.

    Business Delegate Pattern UML Diagram

    Step 1

    Create BusinessService Interface.

    BusinessService.java

    public interface BusinessService {
       public void doProcessing();
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete Service classes.

    EJBService.java

    public class EJBService implements BusinessService {
    
       @Override
       public void doProcessing() {
    
      System.out.println("Processing task by invoking EJB Service");
    } }

    JMSService.java

    public class JMSService implements BusinessService {
    
       @Override
       public void doProcessing() {
    
      System.out.println("Processing task by invoking JMS Service");
    } }

    Step 3

    Create Business Lookup Service.

    BusinessLookUp.java

    public class BusinessLookUp {
       public BusinessService getBusinessService(String serviceType){
       
    
      if(serviceType.equalsIgnoreCase("EJB")){
         return new EJBService();
      }
      else {
         return new JMSService();
      }
    } }

    Step 4

    Create Business Delegate.

    BusinessDelegate.java

    public class BusinessDelegate {
       private BusinessLookUp lookupService = new BusinessLookUp();
       private BusinessService businessService;
       private String serviceType;
    
       public void setServiceType(String serviceType){
    
      this.serviceType = serviceType;
    } public void doTask(){
      businessService = lookupService.getBusinessService(serviceType);
      businessService.doProcessing();		
    } }

    Step 5

    Create Client.

    Client.java

    public class Client {
    	
       BusinessDelegate businessService;
    
       public Client(BusinessDelegate businessService){
    
      this.businessService  = businessService;
    } public void doTask(){
      businessService.doTask();
    } }

    Step 6

    Use BusinessDelegate and Client classes to demonstrate Business Delegate pattern.

    BusinessDelegatePatternDemo.java

    public class BusinessDelegatePatternDemo {
    	
       public static void main(String[] args) {
    
    
      BusinessDelegate businessDelegate = new BusinessDelegate();
      businessDelegate.setServiceType("EJB");
      Client client = new Client(businessDelegate);
      client.doTask();
      businessDelegate.setServiceType("JMS");
      client.doTask();
    } }

    Step 7

    Verify the output.

    Processing task by invoking EJB Service
    Processing task by invoking JMS Service
    
  • MVC Pattern

    MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application’s concerns.

    • Model – Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
    • View – View represents the visualization of the data that model contains.
    • Controller – Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.

    Implementation

    We are going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly.

    MVCPatternDemo, our demo class, will use StudentController to demonstrate use of MVC pattern.

    MVC Pattern UML Diagram

    Step 1

    Create Model.

    Student.java

    public class Student {
       private String rollNo;
       private String name;
       
       public String getRollNo() {
    
      return rollNo;
    } public void setRollNo(String rollNo) {
      this.rollNo = rollNo;
    } public String getName() {
      return name;
    } public void setName(String name) {
      this.name = name;
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create View.

    StudentView.java

    public class StudentView {
       public void printStudentDetails(String studentName, String studentRollNo){
    
      System.out.println("Student: ");
      System.out.println("Name: " + studentName);
      System.out.println("Roll No: " + studentRollNo);
    } }

    Step 3

    Create Controller.

    StudentController.java

    public class StudentController {
       private Student model;
       private StudentView view;
    
       public StudentController(Student model, StudentView view){
    
      this.model = model;
      this.view = view;
    } public void setStudentName(String name){
      model.setName(name);		
    } public String getStudentName(){
      return model.getName();		
    } public void setStudentRollNo(String rollNo){
      model.setRollNo(rollNo);		
    } public String getStudentRollNo(){
      return model.getRollNo();		
    } public void updateView(){
      view.printStudentDetails(model.getName(), model.getRollNo());
    } }

    Step 4

    Use the StudentController methods to demonstrate MVC design pattern usage.

    MVCPatternDemo.java

    public class MVCPatternDemo {
       public static void main(String[] args) {
    
    
      //fetch student record based on his roll no from the database
      Student model  = retriveStudentFromDatabase();
      //Create a view : to write student details on console
      StudentView view = new StudentView();
      StudentController controller = new StudentController(model, view);
      controller.updateView();
      //update model data
      controller.setStudentName("John");
      controller.updateView();
    } private static Student retriveStudentFromDatabase(){
      Student student = new Student();
      student.setName("Robert");
      student.setRollNo("10");
      return student;
    } }

    Step 5

    Verify the output.

    Student: 
    Name: Robert
    Roll No: 10
    Student: 
    Name: John
    Roll No: 10
    
  • Visitor Pattern

    In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class. By this way, execution algorithm of element can vary as and when visitor varies. This pattern comes under behavior pattern category. As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the element object.

    Implementation

    We are going to create a ComputerPart interface defining accept opearation.KeyboardMouseMonitor and Computer are concrete classes implementing ComputerPart interface. We will define another interface ComputerPartVisitor which will define a visitor class operations. Computer uses concrete visitor to do corresponding action.

    VisitorPatternDemo, our demo class, will use Computer and ComputerPartVisitor classes to demonstrate use of visitor pattern.

    Visitor Pattern UML Diagram

    Step 1

    Define an interface to represent element.

    ComputerPart.java

    public interface ComputerPart {
       public void accept(ComputerPartVisitor computerPartVisitor);
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete classes extending the above class.

    Keyboard.java

    public class Keyboard implements ComputerPart {
    
       @Override
       public void accept(ComputerPartVisitor computerPartVisitor) {
    
      computerPartVisitor.visit(this);
    } }

    Monitor.java

    public class Monitor implements ComputerPart {
    
       @Override
       public void accept(ComputerPartVisitor computerPartVisitor) {
    
      computerPartVisitor.visit(this);
    } }

    Mouse.java

    public class Mouse implements ComputerPart {
    
       @Override
       public void accept(ComputerPartVisitor computerPartVisitor) {
    
      computerPartVisitor.visit(this);
    } }

    Computer.java

    public class Computer implements ComputerPart {
    	
       ComputerPart[] parts;
    
       public Computer(){
    
      parts = new ComputerPart&#91;] {new Mouse(), new Keyboard(), new Monitor()};		
    } @Override public void accept(ComputerPartVisitor computerPartVisitor) {
      for (int i = 0; i &lt; parts.length; i++) {
         parts&#91;i].accept(computerPartVisitor);
      }
      computerPartVisitor.visit(this);
    } }

    Step 3

    Define an interface to represent visitor.

    ComputerPartVisitor.java

    public interface ComputerPartVisitor {
    	public void visit(Computer computer);
    	public void visit(Mouse mouse);
    	public void visit(Keyboard keyboard);
    	public void visit(Monitor monitor);
    }

    Step 4

    Create concrete visitor implementing the above class.

    ComputerPartDisplayVisitor.java

    public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
    
       @Override
       public void visit(Computer computer) {
    
      System.out.println("Displaying Computer.");
    } @Override public void visit(Mouse mouse) {
      System.out.println("Displaying Mouse.");
    } @Override public void visit(Keyboard keyboard) {
      System.out.println("Displaying Keyboard.");
    } @Override public void visit(Monitor monitor) {
      System.out.println("Displaying Monitor.");
    } }

    Step 5

    Use the ComputerPartDisplayVisitor to display parts of Computer.

    VisitorPatternDemo.java

    public class VisitorPatternDemo {
       public static void main(String[] args) {
    
    
      ComputerPart computer = new Computer();
      computer.accept(new ComputerPartDisplayVisitor());
    } }

    Step 6

    Verify the output.

    Displaying Mouse.
    Displaying Keyboard.
    Displaying Monitor.
    Displaying Computer.
    
  • Template Pattern

    In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class. This pattern comes under behavior pattern category.

    Implementation

    We are going to create a Game abstract class defining operations with a template method set to be final so that it cannot be overridden. Cricket and Football are concrete classes that extend Game and override its methods.

    TemplatePatternDemo, our demo class, will use Game to demonstrate use of template pattern.

    Template Pattern UML Diagram

    Step 1

    Create an abstract class with a template method being final.

    Game.java

    public abstract class Game {
       abstract void initialize();
       abstract void startPlay();
       abstract void endPlay();
    
       //template method
       public final void play(){
    
    
      //initialize the game
      initialize();
      //start game
      startPlay();
      //end game
      endPlay();
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete classes extending the above class.

    Cricket.java

    public class Cricket extends Game {
    
       @Override
       void endPlay() {
    
      System.out.println("Cricket Game Finished!");
    } @Override void initialize() {
      System.out.println("Cricket Game Initialized! Start playing.");
    } @Override void startPlay() {
      System.out.println("Cricket Game Started. Enjoy the game!");
    } }

    Football.java

    public class Football extends Game {
    
       @Override
       void endPlay() {
    
      System.out.println("Football Game Finished!");
    } @Override void initialize() {
      System.out.println("Football Game Initialized! Start playing.");
    } @Override void startPlay() {
      System.out.println("Football Game Started. Enjoy the game!");
    } }

    Step 3

    Use the Game‘s template method play() to demonstrate a defined way of playing game.

    TemplatePatternDemo.java

    public class TemplatePatternDemo {
       public static void main(String[] args) {
    
    
      Game game = new Cricket();
      game.play();
      System.out.println();
      game = new Football();
      game.play();		
    } }

    Step 4

    Verify the output.

    Cricket Game Initialized! Start playing.
    Cricket Game Started. Enjoy the game!
    Cricket Game Finished!
    
    Football Game Initialized! Start playing.
    Football Game Started. Enjoy the game!
    Football Game Finished!