Introduction to MVC Patterns

Source: Internet
Author: User

Java is an object-oriented language and a powerful tool for implementing object-oriented programming. In practical programming, we should use and exert maximum efficiency. However, it is not simple to use object-oriented programming to develop a good Java application independently, especially for large and medium-sized programs. It is based on object-oriented programming, people will be the actual application of a large number of analysis, summary, and thus summed up a number of standard design patterns. By applying these design patterns to your actual projects, you can minimize the design problems that arise during the development process and ensure that the project is completed in a timely manner.

   Introduction to MVC patterns

The model-View-controller (MODEL-VIEW-CONTROLLER,MVC) pattern is designed for applications that need to provide multiple views of the same data. It is a good way to achieve the separation of the data layer and presentation layer, especially for the development of user graphical interface related applications, as shown in Figure 1. The basic structure in the schema is defined as:

The controller is used to handle user commands and program events;

Model maintains data and provides data access methods;

The display of the view data.

The basic implementation process of the MVC pattern is:

1. The controller (such as the main program entry in Java) to create a new model;

2. The controller creates one or more view objects and relates them to the model;

3. The controller changes the state of the model;

4. When the state of the model changes, the model automatically refreshes the associated view.



Figure 1 MVC Pattern Basic structure

The Java application to be implemented in this article is when the user enters the radius of a sphere in a graphical user interface, the program displays the volume and surface area of the sphere. We first use the basic MVC pattern to implement the above program, and then use a different number of models, views, controller structure to extend the program.

   Basic MVC pattern

The program consists of three classes, namely Sphere class, TextView class and Spherewindow class. Where the sphere class plays the role of model, the TextView class is the view role, and the Spherewindow class is the controller role.

Java implements the MVC programming pattern through specialized class observable and observer interfaces. The implementation of UML class diagram and MVC pattern is shown in Figure 2.



Figure 2 UML class diagram of the MVC pattern

As can be seen from Figure 2, the model class must inherit the observable class, and the view class must implement Interface observer. Precisely because the structure is implemented, the model automatically refreshes the associated view when the model changes (when the controller changes the state of the model). Its UML sequence diagram can be represented as Figure 3.

Model class sphere, you must extend the observable class, because in the observable class, the method Addobserver () relates the view to the model and notifies the view by Method Notifyobservers () when the model state changes. The key code for implementing the MVC pattern is:

Import Java.util.observable;class Sphere extends observable{....public void Setradius (double r) {  Myradius = R;  Setchanged ();         Indicates that the model has changed  notifyobservers ();} ....}




Figure 3 UML sequence diagram of the MVC pattern

The role of the view class TextView class must implement interface observer, which means that class TextView must be implements Observe, and also implement the method update () in it. With this approach, when the state of the model sphere class changes, the update () method in the view associated with the model is automatically invoked to enable automatic refresh of the view. The key code for the view class is as follows:

Import Java.util.observer;import Java.util.observable;public class TextView extends JPanel implements observer{... public void update (Observable o, Object Arg) {  Sphere balloon = (Sphere) o;   Radiusin.settext ("+f3.format (Balloon.getradius ())");  Volumeout.settext ("+f3.format (Balloon.volume ())");  Surfareaout.settext ("" + F3.format (Balloon.surfacearea ())); ......}


The Spherewindow class, as a controller, primarily creates a new model and view, relates the view to the model, and handles the event, where the key code is:

Public Spherewindow () {super (' Spheres:volume and surface area '); model = new Sphere (0, 0, 100); TextView view = new TextView (); Model.addobserver (view); View.update (model, NULL); View.addactionlistener (this); Container C = Getcontentpane (); C.add (view);} public void actionperformed (ActionEvent e) {JTextField t = (JTextField) e.getsource ();     Double r = double.parsedouble (T.gettext ()); Model.setradius (r);}


The program is written through the MVC pattern in Java and is extremely well-extensible. It can easily implement the following functions:

1. Implement multiple views of a model,

2. Use multiple controllers;

3. When the model changes, all views are automatically refreshed;

4. All controllers will work independently of each other.

This is the benefit of the Java programming model, which allows you to easily add many program features simply by modifying or adding new classes on previous programs. Many of the previously developed classes can be reused, and the program structure simply no longer needs to be changed, the various types of mutual independence, easy to group development, improve development efficiency.

One model, two views, and one controller

We discuss how to implement a model, two views, and a controller program. When the user enters a sphere's radius in the graphical user interface, the program displays the sphere in addition to the volume and surface area of the sphere. Figure 4 is visible between the 4 classes of the program.



Figure 41 models, two views, and the basic structure of a controller

where the model class and the View1 class do not need to be changed at all, as in the previous case, this is the benefit of object-oriented programming. For the Spherewindows class in the controller, you only need to add another view and associate with the model. The key implementation code is:

 public Spherewindow () {super (" Spheres:volume and surface area ");   Model = new Sphere (0, 0, 100);   TextView TView = new TextView ();   Model.addobserver (TView);   Tview.addactionlistener (this);   Tview.update (model, NULL);   Graphicsview Gview = new Graphicsview ();   Model.addobserver (Gview);   Gview.update (model, NULL);   Container C = Getcontentpane ();   C.setlayout (New GridLayout (1, 2));   C.add (TView);  C.add (Gview); }


Its program output shown in Figure 5.



Figure 5 Output

One model, two views, and two controllers

in the above program, we can only enter the sphere radius through the keyboard, now we modify the above program, using the mouse to enlarge , reduce the shape of the sphere on the right and change the radius of the sphere to get the input of the sphere radius.

The MCV mode at this time is a model, two views and two controllers, the structure of which can be seen in Figure 6, and its UML class diagram can be represented as Figure 7.

where the sphere, TextView, and Graphicsview classes are exactly the same as before. In the main program spherewindows, this class is not directly used as a controller, it controls the new Controller1 and Controller2. The key code for the program is:

Public Spherewindow ()  {   super (' Spheres:volume and surface area ');   Sphere model = new Sphere (0, 0, +);   Textcontroller Tcontroller = new Textcontroller (model);   Graphicscontroller Gcontroller = new Graphicscontroller (model);   Container C = Getcontentpane ();   C.setlayout (New GridLayout (1, 2));   C.add (Tcontroller.getview ());   C.add (Gcontroller.getview ());  }




Figure 61 Basic structure of a model, two views, and two controllers



Figure 71 UML Class diagrams for models, two views, and two controllers

When the program Spherewindow run, move the mouse to the outer circle of the sphere, click Drag to achieve the enlargement and reduction of the sphere, while the sphere radius, surface area and ball volume also change.

   Summary

As can be seen from the above, it is the future direction of Java object-oriented programming that the application with the MVC pattern to the GUI is very good and extensible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.