The application of MVC pattern in J2ME project (i.)

Source: Internet
Author: User
Tags abstract case statement constructor implement interface prepare switch case ticket
Application of Project MVC pattern in J2ME project (i.)
Author: Favoyang email:favoyang@yahoo.com Welcome to Exchange
Keywords:mvc J2ME UI Mode

Content Summary:
This paper briefly introduces the idea of MVC pattern, analyzes the pros and cons of MVC pattern, and finally gives some common MVC pattern practice with MIDP platform. This article is believed to be more or less helpful to any business program developer using the MIDP platform.

Copyright Notice:
This article at the same time published in Www.j2medev.com and my blog (blog.csdn.net/alikeboy), if necessary reprint, there are three ways: 1 contact me and by my consent; 2) and www.j2medev.com have reproduced article cooperation agreement 3 to aggregate my blog via RSS. In addition, the online reprint needs full text forwarding (including the statement of the head of the article), not taken out of context.

Body:

Initial knowledge of MVC pattern
For the first time, realize that the MVC pattern starts with the document-view model adopted by the Microsoft MFC framework. The first time I got in touch with this concept, I was so excited that the procedural framework issues that bothered me for a long time seemed to be solved. Then I went through the description of the MVC pattern in Gof's book, which enhanced some of the understanding of the pattern. It should be said that the MVC framework is an evergreen tree in the field of programming and one of the most important patterns in the GOF model. This classic pattern is widely used, and there are too many program architectures under this framework, from the early application to the now popular web. And because of their different needs, MVC has a lot of variants. Understanding MVC is a required course for every program designer, and it's best to be proficient.

I do not intend to introduce this model in detail, because the details are more complex, my tongue clumsy is not easy to say clearly, we should refer to the model of books, any one than I want to speak clearly. So it's all over here. The MVC pattern is the abbreviation for Model-view-controller, which is translated as "model-view-controller". The core idea of MVC is separation. Model is the abstraction of the entity class; View is the representation of model on the screen; Controller is the coordinator. Some friends may find that controller's description is somewhat vague, don't worry, this will be talked about. Probably because it's too famous, every implementation of the MVC pattern has a big source, but they're all called mvc!!. Get a beginner to confused. Often abused, and finally get m.v.c. The coordination between the three is very confusing. This is not really their fault, the key to clarify the idea is just mentioned a word "separation." Although the MVC implementation is different, the idea is consistent.

Advantages and disadvantages of MVC pattern
First talk about the advantages:
1) will m.v.c. Separation allows different experts to take charge of different modules, in general, M is responsible for the experts who are familiar with the database, network transmission, and V to the experts who have research on the UI. This is tempting for project managers, and the Division of labor means that the process of software development can be improved and processed according to traditional division of responsibilities. You can also focus on one area for developers. The premise of this is that the interface is clear, and the idea of separation of MVC is providing a foundation for it.
2 Once the part of V changes, can be quickly reconstructed without causing the whole project rework. Some of the changes in the software performance layer today are so fast ...
3 m part, because it is abstract enough to be easily reused, in line with OO ideas. On the other hand, we can use JUnit and other unit testing tools to test the m to ensure the quality of the project.

After talking about the advantages and then to see the shortcomings:
1) using the MVC pattern (and other recent patterns) implies that we can improve the readability and robustness of the program by generating more classes. The downside of the attachment is the expansion of the number of classes. To say a joke, MVC is like a baking powder, is the most convenient code expansion agent, I believe we all have a deep experience:
2 MVC Although defines the meaning of the m.v.c, but is not specific, and there is no very clear connection between the three fixed. So there has been a lot of controversy in other areas except view, and everyone wants to take their own understanding as a positive solution. In particular, "model in the end is the screen data collection or Entity Data", "the role of the controller" is two frequently debated issues. There are a lot of MVC variants mentioned earlier, which leaves a lot of pitfalls for beginners. The following combination of examples will analyze several common practices.
3 The implementation cost of MVC is high. Note, however, that this is relative, and the larger the project is, the better it can be seen.


Common pattern of MVC practices
Here are some of the common practices in the MIDP platform, and finally I am accustomed to practice

M-v form (or mc-v, M-VC)

This is also a common method in J2ME, refining the idea that this method is based on the screen as an organizational unit, so it is suitable for the development of RAD tools. A screen and its controls are abstracted into a VC class that has a private model object that represents the data elements to be used on the screen. Screen objects do not hold any entity data, which is organized in the model object. Probably because the screen object is very intuitive, the role of the controller is not clear (most of its functions are view or model replaced, depending on your implementation), so also often called as Model-view mode. The form is as follows:
Class MyFrame Extend frame{
Private model model;
private Stringitem name;
MyFrame (model model) {
This.model=model;
Name=new Stringitem (Model.getname ());//Request model data
Append (name);
}
}

Class model{
Private String name= "m-c pattern";
Public String GetName () {//This is a service interface
return name;
}
}
What we see above is a typical m-v model, and we can understand the meaning of this screen-centered separation. Model to organize the screen data, view to model for the data they want to display, note that this operation must be through the pre-negotiated interface access, rather than direct operation. If there is a complex transaction logic (the user selected some kind of operation), someone put it on the model side, but also someone put on the view side, but generally on the model side, then model with a serious controller color.

The advantages of this form are very intuitive and also limited to the separation of display and data. If you often see the article j2medev.com webmaster Mingjava, you can see that most of the examples he wrote are this pattern. And this pattern is often used in RAD tools.

The disadvantage of this pattern is that it encourages you to start thinking on the screen just as Rad does, which often leads you to the rad trap of not thinking about the process of the transaction first, but directly targeting the user interface to analyze the problem, which often kills your overall idea.

The MVC pattern used in Sun Blueprints:smart ticket

The famous Blueprint Program Smart ticket uses the MVC pattern, and this pattern helps sun programmers quickly update the view section of smart ticket from MIDP1.0 to MIDP2.0 when MIDP2 is released.

Sun has designed and improved this pattern for MIDP features, and it is a standard method in Sun's solution, but Controller has become a huge transaction processor, and all the user requirements collected by the UI object are forwarded to controller processing. A set of constants is stored inside the controller. In a method in the form of a Dispose (int id) A HUGE switch case statement handles different requests based on the comparison of different constants. This technique sometimes also calls controller a processor, or a screen navigator. The main focus of this model is to deal with frequent screen navigation in J2ME.

Many people feel that it is a good way to change controller into a huge transaction processor in J2ME. I have reservations about that.

Simplified MVC in the Ifeedback

To significantly reduce the number of classes, Ifeedback's authors, encapsulating MVC in a class, representing the separation of the three in different ways, proved to be a great help in reducing the number of classes.
Public abstract class Mvccomponent implements Commandlistener {
Set from outside at beginning
public static display display;

Returns the "Screen object" from the derived class
Public abstract displayable Getscreen ();

Public displayable Preparescreen () throws Exception {
if (getscreen () = null) {
Initmodel ();
CreateView ();
} else {
Updateview ();
}
Getscreen (). Setcommandlistener ((Commandlistener) this);
return Getscreen ();
}

public void Showscreen () {
try {
Display.setcurrent (Preparescreen ());
catch (Exception e) {
E.printstacktrace ();
Alert A = new alert ("Error in showing screen");
A.settimeout (Alert.forever);
Display.setcurrent (a);
}
}

Initialize. If a data is not backed by RMS, make sure
It is uninitilzed (null) before your put in values.
protected abstract void Initmodel () throws Exception;

protected abstract void CreateView () throws Exception;

protected abstract void Updateview () throws Exception;

public abstract void Commandaction (Command C, displayable s);

}
Because all within a class, you don't have to be bothered by the relationship between MVC, which is a compromise of MIDP's limited resources.

My usual practice.

Here is a combination of my understanding of MVC and how to communicate with you. I'm using a UML standard approach that maximizes the sense of separation of thought. First, share your vocabulary with us:

The view represents the screen.
View asks for data from a controller interface and the view collects input from the user, and the view does not process the input, but instead controller different methods based on different input callbacks. The child class of the view usually uses the UI suffix.

Controller Controller
Provides the interface for view invocation, responsible for communication with model. The controller and view share the role of communication with the user.

Model refers to a series of entity objects
Note that the model I understand is not an organizational unit of screen data. Model represents a series of entity objects. By controller and model communication. I think the RAD tool often brings the model representing the collection of screen data to the cause of the confusion of the MVC concept. The model in the RAD tool is roughly equivalent to the role of the controller here.

Controllers are not always associated with model, sometimes just dependencies. and controller often through model of the corresponding life-cycle class to get model objects. In this form, layers of isolation, view and controller closely linked, and model has a high independence, can be very good reuse.

The general process of combining UML design, the various classes of MVC have a corresponding naming habits.
View is called the Boundary Class (boundary Class) ends with the UI
Controller called Controller Class (Control class) ends with workflow
Model called entity Class (entity Class) ends with entity or no suffix
Model corresponds to the Lifecycle Class (Life cycle Class) ending with locator

The underlying classes for boundary classes and control classes are as follows
Baseview.java
/**
* @author Favo
*
* View class
*/
Public abstract class Baseview {

Public abstract Display Getdisplay ();

/**
* Simple to return the packaging screen objects, do not do anything to prepare the screen operation!
*/
Public abstract displayable Getscreen ();

/**
* Create screen
*/
protected abstract void CreateView () throws Exception;

/**
* Update screen
*/
public abstract void Updateview () throws Exception;

/**
* Return to Controller
*/
Public abstract Basecontroller Getcontroller ();

/**
* Prepare the screen
* Return the prepared screen objects
*/
Public displayable Preparescreen () throws Exception {
if (Getscreen () ==null) {
CreateView ();
} else {
Updateview ();
}
return Getscreen ();
}

/**
* Display the current screen
*/
public void Displayscreen () {
try{
Getdisplay (). Setcurrent (Preparescreen ());
catch (Exception e) {
E.printstacktrace ();
Alert al=new alert ("Error", e.tostring () + ' \ n ' +e.getmessage (), null,alerttype.error);
Al.settimeout (Alert.forever);
Getdisplay (). Setcurrent (AL);
}
}

}

Basecontroller.java
/**
* @author Favo
*
* Control class
*/
Public abstract class Basecontroller {
Public abstract Baseview GetView ();
public abstract void Setview (Baseview view);
}


Note that these underlying classes do not produce a complete framework like the MFC framework, but are designed as abstract classes, one that wants to force everyone to implement abstract classes (prevent errors), and hopefully a little more flexibility. So the communication between the two classes depends on the constructor of the subclass that you compose. In general my habit is to initialize a good controller, and then pass the controller as a parameter to the Boundary class constructor, by the constructor of the boundary class to callback controller Setview () to implement. These steps must have some, otherwise will nullpointerexcpetion oh.

While it may be clear theoretically, the complexity of practice is staggering. This is the problem with software development, and too much detail bothers the developer to grasp the big picture. Next, this paper will combine the last design idea, and give a complete design example. To help you understand the use of this model from a practical perspective. Please look forward to it.



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.