Actual MVC Mode

Source: Internet
Author: User
Actual MVC Mode

 

 

Download source code


【Author】: Chen xibo <size: 5 k <Release Date: <browse: 107 〗
Actual MVC Mode

1. MVC
2. Observer Interface
3. Model
4. View
5. Controller
6. Run the program

Program running diagram:

--------------------------------------------------------------------------------
MVC

The Model-View-controller (MVC) structure is designed for applications that need to provide multiple views for the same data, it achieves the separation between the data layer and the presentation layer. Example:

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,

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.
The view retrieves the latest data from the model and refresh itself.
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 model );
}
This interface has a dataUpdate (Model 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 data) {this. data. add (data);} public Data getData (int idx) {return (Data) (data. get (idx);} public int size () {return data. size () ;}// used to register an observer in 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 is used to notify each Observer to refresh the view. public void changeModel (Model model) {data. clear (); // only change the data, and the Model Observer remains unchanged. 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,
This allows you to automatically refresh yourself when the Model data changes.

/* 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 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 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 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) ;}// this method is automatically called when Model data changes to refresh the image public void dataUpdate (model Model) {/** @ todo: implement this Observer method */this. model = model; repaint ();}}

Controller

Okay, the Model and Observer in MVC are all set up. Let's make a Controller: import java. awt. *; import javax. swing. *; import javax. swing. border. *; import java. awt. event. *; public class Controller extends JFrame {Model model = new Model (); View1 view1 = new View1 (model); View2 view2 = new View2 (model ); required jScrollPane1 = new response (); 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 rows: register its observer View1 and View2. model to the 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 can save these codes 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 and 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.