Design Mode: MVC mode (Java)

Source: Internet
Author: User

The Model-View-controller (MVC) structure is an application that provides multiple views for the same data.ProgramDesigned, it achieves the separation between the data layer and the presentation layer. Example:
[Img] Quit
We can see that several groups of data in the figure are displayed in different forms (views). One is a table style and the other is a graphic style.

MVC divides such applications into three object types:
Model: maintain data and provide data access methods.
View: A Visual View of some or all data of the model.
Controller: Process events.
The following are typical MVC communication methods,
[Img] http://www.javable.com/columns/serv_side/workshop/11/1.gif#/img]

Events are handled by the controller. The controller receives user events and changes the model based on the event type.
The view is registered in the model in advance. When the model data changes, each view that has been registered with the model is immediately notified.
View get the latest data from the module and refresh yourself.
To implement MVC, the most important part is to use the Observer Pattern in design pattern. The observer mode allows an object to notify multiple observers when the observed object is modified ).

The following describes how to use the obserer mode to implement the MVC program structure. In my example, I want to show an example of student age. The age of each student is displayed in the form of a list and a graph. When the age changes, the display is automatically updated.

Observer Interface

To notify multiple observers when the observed object is modified, a small interface is usually required between the observer and the observer, as shown below:
/* File: observer. Java */
Public interface observer
{
Public void dataupdate (model );
}
This interface has a dataupdate (model) method. Once this interface object is implemented, it becomes an observer.

Model

Create a data model. In my example, a data object is first created:
/* File: Data. Java */
Public class data
{
Public int value; // student age
Public string name; // Student name
}
Create a model:
/* File: model. Java */
Import java. util .*;
Public class model
{
Arraylist DATA = new arraylist ();
Arraylist observer = new arraylist ();
Public Model ()
{Super ();
}
Public Model (INT [] value, string [] Name)
{
For (INT I = 0; I <value. length; I ++)
{
Adddata (value [I], name [I]);
}
}
Public Model (data [] data)
{
For (INT I = 0; I <data. length; I ++)
{
Adddata (data [I]);
}
}
Public void adddata (INT value, string name)
{
Data DATA = new data ();
Data. value = value;
Data. Name = Name;
This. Data. Add (data );
}
Public void adddata (data)
{
This. Data. Add (data );
}
Public Data getdata (INT idx)
{
Return (data) (data. Get (idx ));
}

Public int size ()
{
Return data. Size ();
}
// Registers the observer with the model.
Public void registerobserver (Observer O)
{
Observer. Add (O );
}
Public void removeobserver (Observer O)
{
Observer. Remove (O );
}
// When the data changes, the Controller calls this method to notify each observer to refresh the view.
Public void changemodel (Model)
{
Data. Clear ();
For (INT I = 0; I <model. Size (); I ++)
{
This. adddata (model. getdata (I ));
}
Dataupdate ();
}
Private void dataupdate ()
{
For (iterator I = observer. iterator (); I. hasnext ();)
{
Observer o = (observer) (I. Next ());
O. dataupdate (this );
}
}
}
This model provides various data access methods. And provides a changemodel method for the Controller to access. The registerobserver (Observer O) method is also provided to register the observer with the model.

View

We need to implement a list display style view 1 and a graphical view view2, and let them implement the observer interface, so that when the model data changes, automatically refresh yourself.
/* File: view1.java */
Import javax. Swing .*;
Import java. AWT .*;
Import javax. Swing. Border .*;
Public class view1 extends jpanel implements observer
{
Model model;

Public view1 ()
{
}
Public view1 (Model)
{
Try
{
This. Model = model;
Jbinit ();
}
Catch (exception E)
{
E. printstacktrace ();
}
}
Private void jbinit () throws exception
{
This. setbackground (color. White );
This. setborder (New titledborder (borderfactory. createlineborder (color. Black, 1), "view1 "));
}

Public void paintcomponent (Graphics g)
{
Super. paintcomponent (g );
If (model = NULL) return;
Int x = 20, y = 50;
Int H = G. getfontmetrics (). getheight ();
For (INT I = 0; I <model. Size (); I ++)
{
Data DATA = model. getdata (I );
G. drawstring (data. Name, x, y );
Y + = h;
G. drawstring (string. valueof (data. value), x, y );
Y + = h;
}
}
// When the model data changes, this method is automatically called to refresh the image
Public void dataupdate (Model)
{
/** @ Todo: implement this observer Method */
This. Model = model;
Repaint ();
}
}
/* File: view2.java */
Import javax. Swing .*;
Import java. AWT .*;
Import javax. Swing. Border .*;
Public class view2 extends jpanel implements observer
{
Model model;

Public view2 ()
{
}
Public view2 (Model)
{
Try
{
This. Model = model;
Jbinit ();
}
Catch (exception E)
{
E. printstacktrace ();
}
}
Private void jbinit () throws exception
{
This. setbackground (color. White );
This. setborder (New titledborder (borderfactory. createlineborder (color. Black, 1), "view1 "));
}

Public void paintcomponent (Graphics g)
{
Super. paintcomponent (g );
If (model = NULL) return;
Int x = 20, y = 50;
Int H = G. getfontmetrics (). getheight ();
Int width = This. getwidth ();
Int Height = This. getheight ();
Int Sy = height/model. Size ();
Int SX = width/2;
For (INT I = 0; I <model. Size (); I ++)
{
Data DATA = model. getdata (I );
Int value = data. value;
Int dx = 3;
Int r = 3;
Color c = new color (INT) (255 * Math. random (), (INT) (255 * Math. random (), (INT) (255 * Math. random ()));
Int Cx = SX;
Int Cy = Y + I * sy;
For (Int J = 0; j <value; j ++)
{
G. setcolor (C );
G. drawoval (CX, Cy, R, R );
R + = DX;
}
G. drawstring (data. Name, 25, CY );
}
}
// When the model data changes, this method is automatically called to refresh the image
Public void dataupdate (Model)
{
/** @ Todo: implement this observer Method */
This. Model = model;
Repaint ();
}
}

Controller

All right, the model and observer in MVC are all set up. Let's finally make a controller:
Import java. AWT .*;
Import javax. Swing .*;
Import javax. Swing. Border .*;
Import java. AWT. event .*;
Public class controller extends jframe
{
Model = new model ();
View1 view1 = new view1 (model );
View2 view2 = new view2 (model );
Jscrollpane jscrollpane1 = new jscrollpane ();
Jbutton jbutton1 = new jbutton ();
Jtextfield jtextfield1 = new jtextfield ();
Jtextfield jtextfield2 = new jtextfield ();
Jlabel jlabel1 = new jlabel ();
Jlabel jlabel2 = new jlabel ();
Jlabel jlabel3 = new jlabel ();
Public controller ()
{
Try
{
Jbinit ();
}
Catch (exception E)
{
E. printstacktrace ();
}

}
Private void jbinit () throws exception
{
Data [] DATA = new data [2];
Data [0] = new data ();
Data [1] = new data ();
Data [0]. Name = "Ted ";
Data [0]. value = 20;
Data [1]. Name = "Joy ";
Data [1]. value = 14;
Model. adddata (data [0]);
Model. adddata (data [1]);
// Note the following two lines: register its observer view1 and view2.
Model. registerobserver (view1 );
Model. registerobserver (view2 );

This. getcontentpane (). setlayout (null );
Jscrollpane1.setbounds (New rectangle (0, 0, 3, 3 ));
Jbutton1.setbounds (New rectangle (309,259,101, 27 ));
Jbutton1.settext ("Update ");
Jbutton1.addactionlistener (New java. AWT. event. actionlistener ()
{
Public void actionreceivmed (actionevent E)
{
Jbutton?action=med (E );
}
});
Jtextfield1.settext ("20 ");
Jtextfield1.setbounds (New rectangle (80,254, 52, 30 ));
Jtextfield2.settext ("14 ");
Jtextfield2.setbounds (New rectangle (178,255, 50, 31 ));
Jlabel1.settext ("Age :");
Jlabel1.setbounds (New rectangle (41,226, 47, 23 ));
Jlabel2.settext ("Ted ");
Jlabel2.setbounds (New rectangle (42,252, 35, 33 ));
Jlabel3.settext ("Joy ");
Jlabel3.setbounds (New rectangle (144,255, 31, 31 ));
View1.setbounds (New rectangle (7, 5,225,208 ));
View2.setbounds (New rectangle (234, 4,219,209 ));
This. getcontentpane (). Add (jscrollpane1, null );
This. getcontentpane (). Add (jtextfield2, null );
This. getcontentpane (). Add (jtextfield1, null );
This. getcontentpane (). Add (jlabel2, null );
This. getcontentpane (). Add (jlabel3, null );
This. getcontentpane (). Add (jlabel1, null );
This. getcontentpane (). Add (jbutton1, null );
This. getcontentpane (). Add (view1, null );
This. getcontentpane (). Add (view2, null );
}
// Press the update button to notify the model data to change.
Void jbutton?action=med (actionevent E)
{
Data [] DATA = new data [2];
Data [0] = new data ();
Data [1] = new data ();
Data [0]. Name = jlabel1.gettext ();
Data [0]. value = integer. parseint (jtextfield1.gettext ());
Data [1]. Name = jlabel2.gettext ();
Data [1]. value = integer. parseint (jtextfield2.gettext ());
Model M = new model (data );
This. model. changemodel (m );
}
Public static void main (string [] ARGs)
{
Controller c = new controller ();
C. setsize (475,310 );
C. setvisible (true );
}
}

Run the program

You canCodeSave them as the corresponding source files and execute the following command to compile
Javac controller. Java
Run
Java controller. Class
You can see the effect of program execution,

you can try to change the age of two students. Click the update button to update the view. How can we experience the convenience brought by the MVC structure to the program ?;)

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.