Java implementation of MVC Pattern

A Design pattern which separates the data logic, UI (User Interface) and processing. Here, data logic deals with Model. UI is for View. The processing can be done by Controller.

This design pattern is useful for Web Application Architecture.

Model-View-Controller (MVC) separates data logic (Model), UI (View), and processing (Controller).

The technical implementation is given below.

Java implementation:

This program implements four classes namely MVC_Model, MVC_View, MVC_Controller and MVCEg.

‘Class MVC_Model’ :

  • It creates and holds the data.
  • Member function :get_Data()
  • Member variable : m_data.

‘Class M_View’:

  • It displays the data to user.
  • Member function: displayIt( String msg). where ‘msg’ is a member variable as String.

‘Class M_Controller’:

  • This process the data.
  • It initialises the values to above two classes.
  • Member function: ‘updateItView()’.
  • Here, this function gets the data from MVC_Model and use the MVC_View function displayIt().

‘Class MVCEg’:

  • It creates the objects for all classes and make a function call.

Program:

//Class1 for creating data logic

class MVC_Model {

    private String m_data = "MVC Example Sample text!";

    public String get_Data() {

        return m_data;

    }

}

//class 2 is for UI.

class MVC_View {

    public void displayIt(String msg) {

        System.out.println("Displaying the message: " + msg);

    }

}

//Class 3 is for Processing.

class MVC_Controller {

    private MVC_Model model;

    private MVC_View view;

    public MVC_Controller(MVC_Model model, MVC_View view) {

        this.model = model;

        this.view = view;

    }

    public void updateItView() {

        view.displayIt(model.get_Data());

    }

}

//Main Class to create objects and function calls

public class MVCEg {

    public static void main(String[] args) {

        MVC_Model model = new MVC_Model();

        MVC_View view = new MVC_View();

        MVC_Controller controller1 = new MVC_Controller(model, view);

        controller1.updateItView();

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac MVCEg.java

C:\raji\blog>java MVCEg

Displaying the message: MVC Example Sample text!

Usage of this code: It is useful in Spring MVC, React and Angular Web frameworks.

This is way of creating MVC Design pattern in java. Hope, this code will useful to you.Keep Coding!!!

No comments:

Post a Comment