Use MVC to develop Java applications

Source: Internet
Author: User
Use MVC to develop Java applications

 

 

Download source code


【Author】: leequn1984 【size: 30 kb】【published on: 2005-12-16 」 browse: 98 〗

 

There is an article on the Internet that describes the use of MVC to develop Java applications (included in the appendix). The author is Yan chibing. You can search on google or baidu (it is better to use baidu to search at this time) using the keyword "developing Java applications using MVC pattern. We recommend that you read this article before reading this article.

Related Articles:
(0) Actual MVC Mode
(1) The greedy Snake game I wrote in MVC
(2) Clearance game based on MVC Architecture

I will introduce the MVC mode by implementing and expanding the example in this article. Program output interface:


 


Features required by the Program:
1. enter the Radius, Volume, and Surface area values of the Sphere. The values of the other two attributes change accordingly, the shape of the right sphere also changes.
2. You can use the mouse to drag (including clicking) the sphere to freely implement the shape and size of the sphere, and the values of the three attributes on the left of the sphere change accordingly.
Implementation process:
See the MVC structure of the program.
 

Careful friends will find that I did not use two controllers as the original author. Here I use a Controller, a Model, and two views ). The figure is converted to text:
1. The controller SphereWindow class creates a model class Sphere. The two view classes TextView and GraphicsView (see the three arrows pointed by the SphereWindow class in the figure)
2. When the Controller changes the model status, the model automatically refreshes the relevant view (corresponding to the three arrows in the middle of the graph)
Design Concept:
1. the Sphere class stores the values of the three attributes of the Sphere and provides the set & get Operation Method for them. Because it is a model class, it must inherit the Observable class. Note, setChanged (); yyobservers (); must be added to set values to notify the view. I have changed and the view associated with me has to be changed accordingly.
2. The View class must implement the Observer interface. After the model changes, the update () method you write in the view is called.
How does the view change? The computer processes data. The view changes are actually because the data is being transformed. Where does the data come from? Isn't it the get () method called in the model? How to call the set () method of the model? It is obvious that the controller is needed to implement it. Generally, the controller is the main program containing the main () method.
3. To achieve program interaction, add event processing in the Controller program SphereWindow to set the data values in the model at any time. It should be noted that, in order to fully satisfy the functions of the program, you must note some logical relationships during the design, such as which controls will be affected when a widget changes. In addition, to improve the program, it is best to provide an exception handling that captures illegal characters.
This is the only thing that can be written in a hurry. I hope you will get some benefits.

Appendix:Use MVC to develop Java applications
Java is an object-oriented language and a powerful tool for implementing object-oriented programming. In actual programming, we should use and exert its maximum efficiency. However, it is not easy to develop a good Java application, especially large and medium-sized programs, independently using the object-oriented programming idea. Based on the idea of object-oriented programming, people have analyzed and summarized a lot of practical applications, so as to sum up many standard design patterns. The rational use of these design patterns to your actual projects can minimize design issues during the development process and ensure that the project is completed on schedule with high quality.

   Introduction to MVC Mode

The Model-View-Controller (MVC) mode is designed for applications that need to provide multiple views for the same data. It separates the data layer from the presentation layer, and is especially suitable for developing applications related to the user graphic interface. See figure 1. The basic structure of the schema is defined:

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

The model maintains data and provides data access methods;

View data display.

The basic implementation process of the MVC mode is:

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

2. The controller creates one or more view objects and associates them with the model;

3. The controller changes the model status;

4. When the model status changes, the model automatically refreshes the view related to the model.

Figure 1 Basic Structure of the MVC Mode

The Java application to be implemented in this article is to display the volume and surface area of a sphere when you enter the radius of a sphere on the graphical user interface. We first use the basic MVC mode to implement the above program, and then use different numbers of models, views, and controller structures to expand the program.

   Basic MVC Mode

The program consists of three classes: sphere class, textview class, And spherewindow class. The Sphere class assumes the role of model, the textview class is the view role, and the spherewindow class is the Controller role.

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

Figure 2 UML diagram of MVC Mode

As shown in figure 2, the model class must inherit the observable class, and the View class must implement the interface observer. Because of the above structure, when the model changes (when the Controller changes the state of the model), the model will automatically refresh the relevant view. The UML sequence diagram can be expressed as Figure 3.

The model class sphere must be extended to the observable class, because in the observable class, the method addobserver () associates the view with the model. When the model status changes, the notifyobservers () method is used to notify the view. The key code for implementing the MVC mode 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 in MVC Mode

The TextView class of the View class must implement the interface Observer, which means that the class TextView must be implements Observe, and the method update () must be implemented (). With this method, when the status of the model Sphere class changes, the update () method in the view associated with the model will be automatically called to automatically refresh the view. The key code of 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())); }......}

As the Controller, the SphereWindow class mainly creates a Model and a View, associates the view with the Model, and processes events. 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);}

This program is written in the MVC mode in Java and has excellent scalability. It can easily implement the following functions:

1. implement multiple views of a model;

2. Multiple controllers are used;

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 mode. You only need to slightly modify the previous program or add new classes to easily add many program functions. Many classes developed previously can be reused, and the program structure does not need to be changed at all. Each type is independent of each other, which facilitates group development and improves development efficiency.

   One model, two views, and one controller

Next we will discuss how to implement a model, two views, and a controller program. When you enter the radius of a sphere in the graphical user interface, the program displays the sphere in addition to the volume and surface area of the sphere. See Figure 4 between the four classes of the program.

Figure 4 basic structure of a model, two views, and a controller

Among them, the Model class and View1 class do not need to be changed at all, just like the previous one, which is the benefit of object-oriented programming. For the SphereWindows class in Controller, you only need to add another view and associate it 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);  }

The program output result is shown in Figure 5.

Figure 5 output result

   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 and use the mouse to zoom in and out the sphere image on the right and change the sphere radius, to obtain the input of the sphere radius.

In this case, the MCV mode is a model, two views, and two controllers. Its structure can be shown in Figure 6. Its UML class diagram can be represented in figure 7.

The Sphere, TextView, and GraphicsView classes are exactly the same as the previous classes. In the main program SphereWindows, this class is not directly used as the Controller, it controls the creation of Controller1 and Controller2. The key code of this program is:


     public SphereWindow()  {   super(“Spheres: volume and surface area”);   Sphere model = new Sphere(0, 0, 100);   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 6 basic structure of a model, two views, and two controllers

Figure 7 UML class diagram of a model, two views, and two controllers

When the SphereWindow program is running, move the mouse to the outer circle of the sphere, click and drag to zoom in and out the sphere, and the sphere radius, surface area, and volume also change.

   Summary

From the above introduction, we can see that the MVC mode achieves extremely good scalability of applications related to the graphic user interface, and is the future direction of Java object-oriented programming.

Source: http://www.javaresearch.org/index.jsp

Related Article

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.