Collections in MVC architecture

My question concerns the use of collections of entities in a database-access MVC architecture. An example similar to my situation would be a Corporation, which (among other attributes) has a collection of Departments, which (among other attributes) has a collection of Projects, which (among other attributes) has a collection of Employees.
Sometimes, I may want information such as all the Employees in the corporation, which would necessarily involve retrieving all the entities from the database. Other times, I may only want the employees in a certain Department, in which case I wouldn't want to waste the time population all the Department beans with Project and Employee information.
Basically, I'm not sure how to best go about populating Javabeans that contain other Javabeans containing other Javabeans. Obviously, when I go to retrieve a Corporation bean, I don't always want all the Departments, Projects, and Employees. However, it seems like it would be using a lot of redundant code to have one factory that returns just the Department base information (without it's Employees), one factory that returns all the Departments and their Projects (but not the Employees), one factory that returns all the Employees for a given Project (but not ALL the Projects and their Employees), and so on.
I've read plenty of MVC tutorials (and even taken a course in it), but I've never really seen a basic situation such as this addressed. What is the best way to go at this situation? Does anyone know of any tutorials/examples that are similar to this situation?

First let's say your post reminded me my previouse Project where i faced exactly this topic.( not a problem may say ) :)
That's it orr94 ! No MVC related topic, says about these. this may be referenced in your experience of Programming and System Design, with the knowledge of OOP, implementing DBs, Performance issues, and so on...
Simply i can tell you, by my experience, try to feel ( and then find ) what your system is supposed to do? and how it does that?
In a situation when you should give many reports, collecting your information, and the main part is GIVING THE LISTS OF REPORTS, just try to load all of your data. ( here first time spends much time, but after that no time is needed for DB operations. you every time read from your objects ( makin' them Updatable )
But if number of the times you should gather this information, is such small that it dosn't actualy needed to read more than wanted.
So see that there is NO GENERAL ANSWER to this question. ( i found it on that project, spending a month to find any answers. )
YOU SHOULD FIND YOUR ANSWER. try feeling your system by real-time TESTS, that would make you sure about a solution.
P.S. Now as a tip
Create a Database Logic Bean which all related methods go in for CRUD operations on entities, then as friends said, try puttin some flags for reading entities ( e.g in your constructors which use DB bean methods )
and then try different approaches readin the data, see which makes sense to your system.
As the last point, what chintat said ( A Getter() which reads the from db that lists ) is not a good solution, where each call to that getter(), where it'd be many calles, attemps to access db!!! you should read once, then getter() returns a reference ( maybe readonly ) to that list.
I think the question is when to read, where YOU SHOUD FIND THE ANSWER. ;)
nice post, i hope it helps. ;)
Behrad

Similar Messages

  • Database access in a MVC architecture

    Hi!
    I'm a bit confused with regards to where the database access code should be put in a MVC architecture. From reading various articles and posts on this forum, there seem to be a lot of different opinions.
    Some seem to put the database access code in the controller servlet(or JSP), while some seem to use helper classes from the JavaBeans, while a few people even seem to access the database directly from the JavaBean.
    My questions is: What is the best place to put the database stuff in a MVC architecture? An explanation as to why a particular solution is the best would be great..
    Thanks!
    regards,
    Vidar

    Let's say I have a class called Department that contains methods like getName(), getId(), setName(), etc... The Department class is my business object. To save and load Departments from a database, I have a class called DepartmentManager. The DepartmentManager saves and loads the departments to the database, and has methods like saveDepartment(), saveDepartments(), loadDepartment(), getDepartments(), etc... In some cases, my manager classes also caches the results so they don't have to load from the database each time. Often times, the manager class is a singleton. My Department class has no idea how it is persisted, or that it is part of a cache. It just knows about itself. The DepartmentManager is resonsible for managing all the persistance and lookup functionality for Departments.
    Therefore, if I have a JSP page that needs to display Departments, my code might look like:
    DepartmentManager dm = DepartmentManager.getManager();
    ArrayList listDepartments = dm.getDepartmentList();
    for (int i = 0; listDepartments != null && i < listDepartments.size(); i++) {
         Department dept = (Department)listDepartments.get(i);
         out.println("<option value=\"" + dept.getId() + "\">" + dept.getName());
    }If I had a specific Department I needed, I would get it as follows:
    DepartmentManager dm = DepartmentManager.getManager();
    Department dept = dm.getDepartment(nId);

  • How to use a  MVC architecture

    i dont know how to use a MVC architecture,what are the files has to be needed to create a MVC architecture,right now iam using jsp file and a java file .in jsp file i just use the usebean tag

    http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html

  • Javabeans in MVC architecture

    Hi
    Building a web application based on MVC architecture. I am new at this so my implementation may not be correct. My Javabeans are representations of SQL DB tables. So, e.g. I have a Customer table in my SQL database, I would have a CustomerBean to represent this table.
    My problem is that Javabeans can only have empty constructors. So how can I get a single record from my customer table? Currently, I am using a method to get this record.
    E.g.
    CustomerBean customer = new CustomerBeanImpl();
    customer.setRecord(primaryKeyOfCustomerTable);
    In setRecord(int PK) method, I execute a SQL query to retrieve the record with that primary key and set all the instance variables for that object.
    I find that this method "not elegant".
    However, if I break the requirements of Javabeans, i.e to implement non-empty constructors, i.e.
    Customer customer1 = new Customer(primaryKey1);
    this would be better. In this case, my class is not a JavaBean anymore.

    Thanks. So, I conclude from your reply that Javabeans
    must have empty constructors. That's what I thought
    too. Until I was looking at an example from "Core
    servlets and JSPs" and came across an example where
    the class used (if anyone is interested, it is
    "TravelCustomer.class" in page 365 of the book) is not
    an Javabean per se, as it did not have a empty
    constructor but was used in the <jsp:useBean> tag like
    any other Javabean!
    That got me confused. Anyone care to explain this?As you know, <jsp:useBean> first checks whether a reference to the specified class exists as an attribute under the specifed id and scope.
    If the reference is found, then the scripting variable is set to that reference. If not found, then <jsp:useBean> checks whether the class can be instantiated and has a no-args constructor. If yes, an object of that class is instantiated (in Tomcat using Beans.instantiate) and the reference is stored as an attribute in the specified scope as well as in the scripting variable.
    In the "Core Servlets..." example, the TravelCustomer object is always instantiated in a servlet and its reference saved as a session attribute with id = "customer". The servlet then forwards to a JSP that includes:
    <jsp:useBean id="customer" class="coreservlets.TravelCustomer" scope="session" />Since the "customer" attribute is always present, the useBean never has to instantiate a TravelCustomer object and so the lack of a no-args constructor does not come into play.
    I'm not sure if this is good or bad practice, but that's why it works.

  • Sap XI application can  be developed based on the MVC architecture in java?

    MVC architecture
    Jsp-->servlet--
    >database.   
    <--<<--
    (front-end)     (business logic)         (data)
    Can anyone explain one process flow  in sap xi with java.
    I would be most thankful to you if you answer me.
    Thanks in advance
    Jeevan

    Hi jeevan
    SAP XI pretty much mimics MVC
    For eg, you create the design objects in IR (View)
    the controller is the J2ee engine of the (WAS server) (controller)
    The model is the database underneath
    regards
    krishna

  • Suggest some docs to do design my Webdynpro-MVC architecture Project

    Hi,
    I am doing design for my project.I'd like to know what are all the steps I have to follow & kept in mind before starting design.could anyone give the link to go thro before start design.I should follow MVC Architecture.
    ie. I should have 4 DC's---(a)UI (b)Service (c)DAI (d)DAM_R3
    Regards,
    Karthick.K.E

    Hello Karthick,
    Hope this document helps you to design WD application
    The title from the document is
    Designing Web Dynpro Applications
    http://help.sap.com/saphelp_nw04/helpdata/en/b1/d1e4f7c633fb47ac8b115087d5f2b6/frameset.htm
    The above link takes you to somehow to wrong title being Example: Using a Foreign Web Dynpro Component
    If you scroll up you find the topic that I mentioned above.
    Good Luck
    Regards,
    Dharmi
    Message was edited by: Dharmi Tanna

  • MVC architecture - how it can be applied to swings

    hi
    I have created a program that gets data from an MS access database and displays it in Swings JFrame, with view, next, previous buttions to traverse through records
    I want to write my program in the MVC architecture model. Though i have read details about it, i am unable to apply it on new programs.
    Any one please help me with an instance of a program or modify the below program to suit the MVC architecture
    thank u
    import java.awt.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.event.*;
    class display extends JFrame implements ActionListener
    ResultSet rs;
    Statement st;
    JTextField tf;
    JLabel l;
    Button b0,b1,b2;
    ResultSetMetaData rsmd;
    display()throws Exception
    tf = new JTextField(10);
    l = new JLabel("Empno: ");
    b2 = new Button("Previous");
    b1 = new Button("Next");
    b0 = new Button("View");
    connection con = new connection();
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    setSize(300,300);
    c.add(l);
    c.add(tf);
    c.add(b0);
    c.add(b1);
    c.add(b2);
    setVisible(true);
    l.setBounds(20, 10,70,35);
    tf.setBounds(20,50, 70,35);
    b0.setBounds(20,90, 70,35);
    b1.setBounds(90,90, 70,35);
    b2.setBounds(170,90, 70,35);
    b0.addActionListener(this);
    b1.addActionListener(this);
    b2.addActionListener(this);
    public void actionPerformed(ActionEvent ae)
    if(ae.getActionCommand().equals("View"))
    try{
    rs.close();
    rs = st.executeQuery("select * from emp");
    if(rs.next())
    tf.setText(rs.getString(1));
    catch(Exception e)
    {System.out.println(e);}
    if(ae.getActionCommand().equals("Next"))
    try
    if(rs.next())
    {tf.setText(rs.getString(1));b2.setEnabled(true);}
    else
    {b1.setEnabled(false);b2.setEnabled(true);}
    catch(Exception e)
    {System.out.println(e);}
    if(ae.getActionCommand().equals("Previous"))
    try
    if(rs.previous())
    { tf.setText(rs.getString(1)); b1.setEnabled(true);}
    else
    {b2.setEnabled(false);b1.setEnabled(true);}
    catch(Exception e)
    {System.out.println(e);}
    class connection
    connection()throws SQLException, ClassNotFoundException
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:dsn1");
         /*st = con.createStatement();
    rs = st.executeQuery("select * from emp");*/
    st = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    rs = st.executeQuery("select * from emp");
    } // connection constructor
    } // end of connection
    }//end of display
    class records
    public static void main(String args[])throws Exception
    display d = new display();
    }

    help full hint use code formating tags
    David

  • Which is more in line with MVC architecture with Struts?

    Hello all
    When using the MVC Model 2 architecture, the JSP's are the view, servlets the control, and the beans are the model. If we say that a control method should represent a specific use case, then in theory, you should be able to call the control method from any interface to request that a specific use case be performed, whether it be over a simple socket connection receiving bytes, or using HTTP.
    However, when using jsp's/servlets, if thr servlet is the control, then it means that the interface must make the request using HTTP and contain a request/response object. But supposing you wanted to change the interface to request the same use case, but makes an http request but supplying XML (instead of several request parameters) which contains the request data, you cannot then simply use the same servlet use-case.
    So what is the solution? If you write another servlet to handle the different request format (XML) it copies a lot of the control code from the other servlet which is a bit messy. Or, would it be correct to write a seperate Controller class (standard Java class), which would contain a set of related use cases, and are called by the servlet. Each use case (which would be a method call in the controller class), would take in its parameter list the exact type and data it needs to complete the use case. In this case the servlets are simply pulling data from the HttpRequest object, converting them to the correct java type to be passed to the controller class you create.
    This introduces an extra layer; the servlet now sits between the request interface and control. It means that the control methods can be called from any type of interface, but is it the right way of doing things, and how would the new control objects be held in the servlet?
    Please could someone give their opinion on which they think is the best way of architecting this?
    Many thanks,
    Shaun.

    Shaun,
    I'm going through the same issues as I try to build my own MVC framework. Struts is useful, but does not cover everything. If you're interested, I've found that the book "Core J2EE Patterns - Best Practices and Design Strategies" by Alur, Crupi and Malks is very helpful. It contains design patterns for all the various tiers. It does not describe a framework, just a set of patterns from which you can pick and choose.
    In the example you describe, one of the applicable patterns is the "Session Facade" which is basically a high-level business interface. The goal is to hide the complexity of the entire business API from the client. The book recommends each facade to correspond to a related set of use cases. e.g. methods in one facade could include OpenAccount, CloseAccount, GetBalance etc. Implementation would be Java classes.
    This facade should be independent of the request protocol and could be used for HTTP, by a Java application, by a web service etc. Usually the facade classes would be located close to the business objects to minimize network delay and traffic.
    In your example, the controller servlet (Struts Action) would invoke services from the Session Facade.
    You're right about this introducing an extra layer. Depending on your present and future needs, you can end up with others such as abstracting the persistence layer. The trade-off is between up-front effort and future flexibility.
    You ask how to reference the new objects. In my case, the initialization servlet calls a factory class method to get references to the facades. These references are stored in an application-specific object that is added as a ServletContext attribute for use by other controller servlets.
    I know this doesn't fully answer your question, but hopefully it helps a little.

  • JSF MVC Architecture Question

    There seem to be two distinct schools of thought on this.
    1 group defines it as such:
    Model = Data
    View = HTML
    Controller = Business Logic and everything else.
    The other group defines it at as:
    Model = Data / Application Logic
    View = HTML
    Controller = accepts user input and instructs model and view to perform actions based on that input, ie. maps end-user action to application response.
    In the case of a JSF application specifically this would mean:
    .xhtml files = View
    POJO backing bean (containing application logic + Faces Servlet) = Controller
    POJO backing bean (containing data) = Model
    OR
    .xhtml files = View
    FacesServlet (the view handler, which processes requests / responses etc) = Controller
    POJO backing bean(s) (containing the data / application logic) = Model
    Any insight provided into this would be greatly appreciated.

    That's pretty interesting topic for me as a beginner and I'll try to talk about that at work and get deeper insight. If I learn something about it, I'll post it here. However I'd like to hear a bit from JSF gurus on that one :)

  • Architecture Issue (MVC)

    ARCHITECTURE DESIGN COMMENTS
    We have designed a java system for one of the crucial projects.After that due to some reasons we are asked to restructure it. Here I?m presenting 2 variations with all the details.
    I sincerely request your comments on this, and if you have a better solution with the existing means(jsp,javabean,servlet) please let us know.
    The basic things I need to know is that:
    1. Feasibility of this model.
    2. performance.
    3. Any drawbacks and how to over come them.
    I MODEL
    (valueobject)
    jsp----->Servlet(Controller)------------------------------->(DBMangager)--------->Database
    (Since this is not taking the image-i could not able to draw the entire thing properly)
    Process
    The process in the first model is that
    1. All the parameter names and values are collected in a HashMap in the controller.
    Ex. Request.getParameterNames()
    while ( e.hasMoreElements () )
    String name = ( String ) e.nextElement () ;
    String val[] = request.getParameterValues ( name ) ;
    hm.put ( name , val ) ;
    2. Then the controller sends it to the constructor of the Assembler.
    try
    fv = new FwAssembler ( hm , txn_no , comp_code ) ;
    3. The assembler segregates the code and assigns to the corresponding value objects.Here value objects are parameters to the Assembler.Means once the corresponding value objects are set, these value objects are set to the Assembler with setValueObjects. So that now the assembler contains value objects which represent the data.
    An extract:
    public FwAssembler(HashMap hm, String tx_no, String comp_code)
    setComp_code(comp_code);
    setTxn_no(tx_no);
    ftran = new FwTransaction(tx_no);
    aprofile = new ApplcantProfile(comp_code);
    cvo=new CompProductsVO(tx_no);
    lfile.logErr("FwAssembler","1");
    The following corrosponds to the automation plan.
    Depending upon the value of strAutomation remaing values will be considered.
    String n1[] = (String[]) hm.get("strAutomation");
    strAutomation = n1[0];
    ftran.setStrAutomation(strAutomation); // this gives whether automation plan is yes or no
    String n270[] = (String[]) hm.get("strDateimplemen");
    try
    if (strAutomation.equalsIgnoreCase("y"))
    String n2[] = (String[]) hm.get("strDateimplemen");
    strDateimplemen = n2[0];
    ftran.setStrDateimplemen(strDateimplemen);
    String n3[] = (String[]) hm.get("decCostinvolve");
    decCostinvolve = Double.parseDouble(n3[0]);
    ftran.setDecCostinvolve(decCostinvolve);
    String n4[] = (String[]) hm.get("vcPartauto");
    vcPartauto = n4[0];
    ftran.setVcPartauto(vcPartauto);
    String n5[] = (String[]) hm.get("intNoworkers");
    intNoworkers = Integer.parseInt(n5[0]);
    ftran.setIntNoworkers(intNoworkers);
    catch (Exception kk)
    lfile.logErr("strAutomation", "Exception kk", kk.toString(),
    kk.getMessage());
    4. Once the Assembler is set, the controller will send Assembler to the DBManager.
    try{
    b = fbean.insertFwworker(fv, txn_no, comp_code);
    catch(Exception bean)
    lfile.logErr("","bean",bean.toString(),bean.getMessage());
    5. DBManger, with the help of value objects will insert the data into the data base.
    6. This method will return true, and if it is true the controller will send it to the next jsp page.Else it will display the error page.
    I I? MODEL
    In my model II- the most significant difference is that :
    While sending the data from Controller to the Assembler I have not used a HashMap, but in my model II, I just send the request object.
    cassembler=new CfcAssembler(request,txn_no,comp_code);
    ofcource what I?m planning is that:
    Instead of putting it in a Constructor I want to send it in a method in that class.
    I had the following advantages got by doing so:
    1. My coding is considerable reduced to a greater extent.
    public CfcAssembler(HttpServletRequest request,String tx_no, String comp_code)
    setStrTrxn(tx_no);
    setStrCompCode(comp_code);
    setSelIcfctype(request.getParameter("selIcfctype"));
    setStrCfcdesc1(request.getParameter("strCfcdesc1"));
    if(request.getParameter("decQty")!=null)
    setDecQty(Double.parseDouble(request.getParameter("decQty")));
    else
    setDecQty(decQty);
    setStrPurpose(request.getParameter("strPurpose"));
    if(request.getParameter("cbEmail")!=null)
    cbEmail=request.getParameter("cbEmail");
    if(request.getParameter("cbPhone")!=null)
    cbPhone=request.getParameter("cbPhone");
    if(request.getParameter("cbPost")!=null)
    cbPost=request.getParameter("cbPost");
    strMethodNotify+=cbEmail+cbPhone+cbPost;
    setStrMethodNotify(strMethodNotify);
    2. My performance I think is improved, because I?m not using any String Arrays.
    3. The readability of the code is also good.
    Where I?m not sure
    In the Assembler class I?m importing the package javax.servlet.HttpServletRequest.
    1.Can this Assembler class is made as a java bean.
    2. Will this model also fulfills the MVC architecture.
    Please fill in me with all the details.Your earliest reply in this matter is highly appreciated,as we are at a crucial stage.
    Thanking you
    pressy

    I would be surprised if your scaling bottleneck occurs dumping an HttpServletRequets parameter list into a Map. So, while there may be a slight performance/memory hit in populating the Map, it should be negligible as everything is already in memory.
    From a design perspective, I like #2 better. You don't want to import the http.servlet classes everywhere in your domain model. You should theoretically be able to switch either your view or your persistence tier without affecting the domain model.
    Servlet classes are tied to a web presentation framework. Not that a sane person would do such a thing, but what if you decided to switch your UI to Swing? Now, all those HttpServletReqeust objects are useless, but a Map still works fine.
    On a more realistic example, what if you decided to switch to SOAP and web services instead? The ServletRequest and SOAP request could both have adapters written that generate the same Map. Now, all your code past the Map is the same regardless of what type of request you receive.
    Now, I have never completely changed my view or even my persistence tier in a real-world application. However, I do see the validity or keeping the model agnostic. So... no Servlet classes should go there. IMHO, that is.
    - Saish
    "My karma ran over your dogma." - Anon

  • How to implement mvc model in designing game architecture

    I have a problem in implementing the mvc architecture in my game designing. I want you to suggest me how should I do it ?
    I have created 3 packages viz : model , view , and controller
    I am confused in which package should include canvas ? which should implement Runnable ? and what actually the model package must include ?
    Also i would like to know that whatever dynamic active background is generated in my game play must it be treated as model or not ?

    Hi
    Here is a good article about this: http://www-128.ibm.com/developerworks/library/wi-arch6/?ca=drs-wi3704
    Mihai

  • Is there a way to specify MVC model in a Wizard?

    I am fairly new to JDeveloper so forgive me if I ask a stupid question....
    In a past web project I used IBM Websphere and Visual Age developing environments. For an upcoming project I am going to be using JDeveloper but with the same basic MVC architecture with the Servlets being the Controllers and JSP as the View. In Websphere there was a wizard that we could use to create a Java Bean based on our SQL statement. Within this wizard we could also select what 'model' we wanted to use and if we chose 'Servlet model' it would not only create the Java Bean but it would also crate the corresponding Servlet, XML file and JSP. All we had to do after that was bring up the JSP in the test environment and everything was hooked together already. If it was a simple select statement then the JSP displayed the results in a table. The JSP could then be facncied up or whatever. What I want to know is if there is something similar to that in JDeveloper. I know there are wizards to create Servlets and JSPs but is there any way to specifiy a 'model' and have everything to connected up without manually going into the code and doing it? I know this is kinda cheating and being lazy but I just wanted to ask if this type of feature existed before going ahead and doing unneccessary work. So if anyone can follow what I am saying and has an answer or perhaps can direct me to some documentation, that would be much appreciated. Thanks in advance for your help!
    Janis

    Janis,
    JDeveloper ships with a handy, built-in J2EE application framework called Business Components for Java that provides a full-functionality J2EE MVC model layer for you.
    You can get a nice overview of the framework's functionality from this whitepaper:
    Simplify J2EE Applications with the Oracle BC4J Framework
    For a quick overview of how the BC4J framework components implement the familiar collections of value objects design pattern for you, see:
    Implement Collections of Value Objects for MVC Apps with BC4J
    To answer your question about the wizards, you can (in no time flat)
    [list]
    [*]Create a new connection in the System Navigator
    [*]Create a new package of BC4J framework components ("New Business Components Package...")
    [*]On the last panel of the BC4J package wizard, you can select existing tables to reverse-engineer into framework data-access and business logic components (view objects and entity objects, respectively)
    [*]Then, you can use one of our other wizards to produce, for example, a BC4J+Struts application, a BC4J+JSP application, or a BC4J+JClient/Swing (rich client) application
    [list]
    Hope this helps.

  • How can i use tag library in the mvc?

    hello
    in some tag libraris such as jakarta tag library and jrun tag library,there is database
    access tag, it provide convenient function to access database from jsp page,but i wonder how can i use such a tag within MVC architecture.
    as we know,in MVC architecture,all requests from the jsp pages are submit to the controller servlet,then the controller manipulate ejb to access database,it don't allow the database access from the jsp page.
    who can tell me how can i combine the tag library with mvc architecture appropriately?
    thank you!

    You can't! If you decide to limit the JSP to be part of the View component, obviously you should not include tags that directly access the database. If the strict MVC architecture is less important to you, then the tags can save coding time. It's your choice.

  • MVC model in Web systems and applications

    MVC model in Web systems and applications
    Object-oriented design model is experience, MVC idea is a user interface for the original. This article discusses how the major application areas in the new Web design patterns and the use of MVC framework. The article first introduced the concept of design patterns and characteristics, and MVC architecture design concepts and analysis of the MVC framework contains several key models. Based on the characteristics of Web applications on how to use patterns and MVC framework made some design ideas.??
    1. Introduction
    1.1 design model
    Object-oriented technology and the emergence of software applications has greatly enhanced the trusted and software quality. Object-oriented programming than previous models to various programming simple and efficient, but the object-oriented design methodology than the previous design methods to complex and much more skill, a good design should be both on the issue of gender, but also to take full account of the problems and needs sufficient interoperability. In the past 10 years, people in the object-oriented technology and the practical application of research to explore certain issues in relation to the creation of a number of good solutions, the so-called object-oriented design patterns. Object-oriented technology is one of the purposes of enhancing the software trusted, and to design model, design programmes in important positions from a deeper sense of meaning and essence embodies trusted. There are many people in the design model definition, which cited Christopher Alexander is the largest design model definition : Each design model is a tripartite rule, which expresses a contextual environment (Context), a problem and a solution. Design models generally following basic elements : model name, the purpose solution effect 1995-1998 code and related design models. There are several classifications design patterns can be divided into a model based on the purpose (Creational), structural type (Structural) and the type of behaviour (Behavioral) three. It is mainly used in the creation of a model-based object model-based structure to deal primarily with the category or combination of objects, used to describe behavior-based model is the main target for the category or how stress and how to allocate responsibilities. Design patterns can be divided into categories based on the scope and target mode model type model dealing with the relationship between the categories and sub-categories, these relations through the establishment of succession in Translation moment to be finalized, are static. Model is targeted at addressing the relationship between the moment of change these relations in the operation, more dynamic. Model features : through the experience acquired in a structured format to write down, avoid encountering the same problems on the first design, exist in different abstract level, in continuous improvement, can be trusted artificial product for the design and best practice in the world to be combined to address larger issues.
    1.2 MVC framework
    MVC was first used in a user interface Smalltalk-80 China. M representative models Model, representatives maps View V, C representatives controller Controller. MVC trusted code with the aim of increasing the rate of data reduction expressed, the data describing the operation and application coupled degrees. Also makes software Keweihuxing, restorative, expansionary, flexibility and packaging of greatly enhanced. Single-user applications are usually incident-driven user interface to the organizational structure. Staff development tool with an interface painting of a user interface interface code based on user input and then prepare to implement the corresponding moves, many interactive development environment encouraged to do so, because it emphasizes first and then a functional interface. Some software design model is the strategy that will be fixed before the code into the regular system of the final. Result is that the procedures and organizations around the user interface elements in the user interface elements of those moves, data storage, applications and functions of the code is used to indicate the way intertwined. In single-user system code structure can be so, because the system will not demand frequent changes. But for a large system such as large Web systems, or e-commerce systems to be applied. Model by incorporating data from a variety of access and control data can be separated to improve distributed system design. MVC design pattern is composed of three parts. Model is the application object, no user interface. Type in the screen showing that it represents the flow of data users. Controller user interface definition response to user input, the users responsible for the action against the Model into operation. Model View data updated to reflect the adoption of data changes.
    2. MVC design pattern,
    An MVC framework for the design of the system includes many models, but with MVC is most closely related to the following three models : Observer, Cambridge and Strategy.
    2.1 Observer models
    MVC through the use of purchase / notification form and the separation of the Model View. View to ensure that their content accurately reflected Model and state. Once Model content changes, there must be a mechanism to allow notification to the relevant Model View, View can be made relevant at the appropriate time updating of data. This design is also more general problems can be solved, the target separation, making a change to the target audience affect others, which targets those who do not know the details of the object being affected. This is described as Observer in the design model. Model type : Observer model is the object-oriented model, it is behaviour-based model. Model purposes : definition of hierarchical dependence relations between objects, or when a target value of the state change, all its dependent relationship with the object are notified and automatically updated. There are a variety of data may show a way, in different ways and may also show. When a way through a changed data, then the other should be able to show immediately that the data change and do accordingly.
    Effect :
    1. Abstract coupling. I only know that it has a target audience of some observers, the observers met each abstract Observer category simple interface, does not know their specific affiliation categories. This makes the coupling between goals and observers smallest and abstract.
    2. Support radio communications. Needless to notify designated observers goals, how to deal with the observer informed decisions.
    3. Possible accidents updated. We update logic, avoiding mistakes updated.
    2.2 Faculty model
    MVC is an important feature of View can nest. Nest can be used for any type of combination of local maps available, but also management of type nest. This thinking reflects the type and mix of components will be equal treatment design. This object-oriented design ideas in the area of Cambridge has been described as a design model. Model types : Cambridge model is the object-oriented model, it is also the structure type model. Model purpose : to target portfolio into tree structures to express "part-whole" level structure. Prepared for the use and combination of individual target audiences with the use of consistency.
    Effect :
    1. Definition of a target portfolio includes simple objects and the structure of the category level. Simple objects may be complex combinations of objects, and can be targeted portfolio mix. This customer-code used in the target areas can use simple combinations target.
    2. Simplify customer-code. Needless to know their customers - a mix of target audiences is a simple target or can use these items in a consistent manner.
    3. Easier to add new types of components. New components can easily be changed to a combination of customer-targeted codes.
    2.3 Strategy model
    Another important characteristic is the MVC can not change the View of changes View response to user input. This often requires a change in response to the logic of the system is very important. MVC to respond to the logic involved in the Controller. Controller of a category level structure could easily change to the original Controller appropriate, a new Controller. View Controller son used to achieve a specific example of such a response strategy. To achieve different response strategy, as long as examples of the use of different types of replacement will Controller. Also in the running time by changing the View Controller for users to change View of response strategies. This View-Controller relationship was described as an example of Strategy design pattern. Model types : Strategy model is the object-oriented model, it is behaviour-based model. Model purposes : definition of a series of algorithms, and their packaging, and ensure that they can replace each other, making algorithms can independently use its customer-change.
    Effect :
    1. Strategy category levels for Context definition of the relevant algorithms can be trusted or behaviour.
    2. Alternative methods of succession. If the direct successor Context, with different acts will be added Context act, the realization of which would algorithm mixed up with Context, Context hard to preserve and expand, but can not dynamically changing algorithms. Will be enclosed in a separate Strategy category algorithms to enable algorithm independent Context change easily cut over expansion.
    3. Can provide the same acts different date.
    4. Strategy-must understand what customers between different.
    5. Context and Strategy communications between costs.
    6. An increase in the number of targets.
    3. MVC in Web application system
    Now some of the distributed systems such as Web-based B2B e-commerce system, suitable for use MVC framework. Through analysis from the perspective of high-level applications can be a target divided into three categories. Category is shown for the target audience consists of a group of commercial rules and data, there is a category that is receiving requests to control commercial target to complete the request. These applications often need to change is shown, such as web style, color, but also need to demonstrate the contents of the display. And the business rules and data to be relatively stable. Therefore, said that the frequent need to change the View objects that the business rules and data model to be relatively stable target, and that the control of the Controller is the most stable. When the system is usually issued after the View objects by artists, designers or HTML/JSP system managers to manage. Controller target applications development personnel from the development and implementation of rules for commercial and business development personnel from the target data, database managers and experts in the field of common completed. Show in Web?? or customers - control logic can be Servlet or JSP, dynamically generated Html. Generally used Servlet better than using JSP. JSP will be better with the Html code of separate codes for page designers and developers of separation efficiency. Servlet and JSP can complete all complete functions, actually JSP eventually converted into a Servlet. And control of the target system exists in every level, the coordination of cross-layer moves. Contain business rules and data objects exist in the EJB layer (EJB-centred model) or Web?? (Web-centred model).
    3.1 View in the Web application system
    View of the system shows that it fully exist in Web??. General by JSP, Java Bean and Custom Tag. JSP can generate dynamic web content using Java Custom Tag easier Bean, but it can show the logic of packaging, and more conducive to modular trusted. Some well-designed in a number of JSP Custom Tag can even be used in different system duplication. Model for control of JSP and Java Bean objects. JSP through Java Bean objects to retrieve the data model, the Model and Controller object is responsible for updating the data on Java Bean. In general, can we devise all possible screen that users can see all the elements of the system. Based on these elements, to identify the public part of passive components and dynamics. Can consider the use of templates means to separate the content generated JSP public, also need to change their generation Html or JSP from a JSP templates to dynamically introduce these different parts (include methods). Another issue to consider is screen option, when dealing with End users request template automatically available to show that the concern that users must know what is the screen components. So can consider all screens on the definition of a centralized document, such as a document or text document java. Taking into account the possibility of changes in future document definition screens, the best use of text documents such as a XML document, so future changes to the recompilation. According to the URL and user input parameters to shine upon the results of a screen, of course, likely to be made on the basis of the outcome of the implementation of actions to choose different results screen. Therefore, the need for a request for matching resources with document (XML), if a URL request several different results, it must specify in the document need to control the flow (a controller object), as well as the corresponding screen different flows.
    3.2 Model in the Web application system
    Model objects represent business rules and business data exist in EJB layer and Web??. In J2EE norms, the system needs some data stored in the database, such as user account information (account model), the company's data (company model), some not recorded in the database. If a user browsing the current catalogue (catalog model), the contents of his shopping (shopping cart model). Which one of these models exist in the data according to their life cycle and scope to decide. In Web?? a HttpSession and ServletContext and Java Bean objects to store data in the EJB layer is a data storage and logic EJB to. Web?? the Java Bean objects stored in the model layer model of the EJB object data copy. Because there are many different EJB tier model targets, so Web?? through a ModelManager to control the EJB layer object model in ModelManger background model can be used for packaging methods. In the EJB layer and the rules have all the data into EJB model is inappropriate. If the database can visit the Dao object model into objects. Dao can be encapsulated and the specific details of the database in the world, if we can write a different table, a number of databases, or even multiple databases. If the orders can be a model for OrderDAO, it may have to deal with Order table, table and OrderItemLines OrderStatus table. Value can also consider the use of targets. Value can be a target of securing long-range targets, because every time the remote object attributes could be a long-range redeployment process will consume network resources. EJB objects in the distance can be used instead target. In the distance, one-time items to be targeted instead of the value of all attributes.
    3.3 Controller in Web application system
    Coordination with the Model View Controller object to the request of users into the system to identify incidents. In Web?? generally a MainServlet (or Main.jsp), and receiving all requests, it can use screen flow management devices (ScreenFlowManger) decided next screen. There is a general request processors RequestProcessor contains all requests are needed to be done to deal with logic, such as the request translated into system events (RequestToEvent). Acting processors usually also includes a request for ClientControlWebImpl, it is logical to deal with the EJB layer in Web?? Acting. In EJB layer, a layer for EJB tier Web ClientController provide the CD visit. Another StateMachine used to create and delete ejb handle Web?? sent to the incident. Controller Another important function is synchronous View and Model data. ModelManger contained in a ModelUpdateManger, it puts events into a Model System assembly that all the needs of synchronous Model, and then notify Listeners do synchronous operation.
    4. Concluding remarks
    In recent years, with the Internet technology development and the emergence of new business models, the Web is based on a large number of applications. On how to design these systems architecture, and gradually there has been some convergence of opinion, the most important point is that its structure should be rational in the open. Demand than ever faster development of technology and design concepts, systems for the future, the cost of upgrading the smallest, research software systems architecture still very useful and necessary.

    Bravo. And your point is?

  • What is the best way to use Swing GUIs in an MVC design?

    I have a question on how to build an application using swing frames for the UI, but using an MVC architecture. I've checked the rest of the forum, but not found an answer to my question that meets my needs.
    My application at this stage presents a login screen to get the userid and password, or to allow the user to choose a new locale. If an Enter action is performed, the userid and password are checked against the DB. If not accepted, the screen is repainted with a "try-again" message. If the Cancel action is performed, the process stops. If a locale action is performed, the screen is repainted with different langauge labels. Once the login process is passed, a front screen (another swing frame) is presented.
    Implementation: I am using a session object (Session, represents the user logging in) that calls the Login screen (LoginGUI, a Swing JFrame object with various components). Session uses setters in LoginGUI to set the labels, initial field entries etc, before enabling the screen. From this point, the user will do something with the LoginGUI screen - could be closing the window, entering a mix of userid and password, or maybe specifying a locale. Once the user has taken the action, if required, the session object can use getters to retrieve the userid and password values entered in the fields.
    The crux of the problem is 1) how will Session know that an action has been taken on the LoginGUI, and 2) how to tell what action has been taken.
    This could be solved by getting LoginGUI to call back to Session, however, I am trying to buid the application with a good separation of business, logic and presentation (i.e MVC, but not using any specific model). Therefore, I do not want LoginGUI to contain any program flow logic - that should all be contained in Session.
    I am aware of two possible ways to do this:
    1. Make LoginGUI synchronised, so that Session waits for LoginGUI to send a NotifyAll(). LoginGUI could hold a variable indicating what has happened which Session could interrogate.
    2. Implement Window Listener on Session so that it gets informed of the Window Close action. For the other two actions I could use a PropertyChangeListener in Session, that is notified when some variable in LoginGUI is changed. This variable could contain the action performed.
    Has anyone got any comments on the merits of these methods, or perhaps a better method? This technique seems fundamental to any application that interfaces with end-users, so I would like to find the best way.
    Thanks in advance.

    Hi,
    I tried to avoid putting in specific code as my question was more on design, and I wanted to save people having to trawl through specific code. And if I had any school assignments outstanding they would be about 20 years too late :-). I'm not sure computers more sophisticated than an abacus were around then...
    Rather than putting the actual code (which is long and refers to other objects not relevant to the discussion), I have put together two demo classes to illustrate my query. Comments in the code indicate where I have left out non-relevant code.
    Sessiondemo has the main class. When run, it creates an instance of LoginGUIdemo, containing a userid field, password field, a ComboBox (which would normally have a list of available locales), an Enter and a Cancel box.
    When the Locale combo box is clicked, the LoginGUIdemo.userAction button is changed (using an ActionListener) and a property change is fired to Session (which could then perform some work). The same technique is used to detect Enter events (pressing return in password and userid, or clicking on Enter), and to detect Cancel events (clicking on the cancel button). Instead of putting in business code I have just put in System.out.printlns to print the userAction value.
    With this structure, LoginGUIdemo has no business logic, but just alerts Sessiondemo (the class with the business logic).
    Do you know any more elegant way to achieve this function? In my original post, I mentioned that I have also achieved this using thread synchronisation (Sessiondemo waits on LoginGUI to issue a NotifyAll() before it can retrieve the LoginGUI values). I can put together demo code if you would like. Can you post any other demo code to demonstrate a better technique?
    Cheers,
    Alan
    Here's Sessiondemo.class
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import java.beans.*;
    public class Sessiondemo implements PropertyChangeListener {
        private LoginGUIdemo lgui;   // Login screen
        private int localeIndex; // index referring to an array of available Locales
        public Sessiondemo () {
            lgui = new LoginGUIdemo();
            lgui.addPropertyChangeListener(this);
            lgui.show();
        public static void main(String[] args) {
            Sessiondemo sess = new Sessiondemo();
        public void propertyChange(java.beans.PropertyChangeEvent pce) {
            // Get the userAction value from LoginGUI
            String userAction = pce.getNewValue().toString();
            if (userAction == "Cancelled") {
                System.out.println(userAction);
                // close the screen down
                lgui.dispose();
                System.exit(0);
            } else if (userAction == "LocaleChange") {
                System.out.println(userAction);
                // Get the new locale setting from the LoginGUI
                // ...modify LoginGUI labels with new labels from ResourceBundle
    lgui.show();
    } else if (userAction == "Submitted") {
    System.out.println(userAction);
    // ...Get the userid and password values from LoginGUIdemo
                // run some business logic to decide whether to show the login screen again
                // or accept the login and present the application frontscreen
    }And here's LoginGUIdemo.class
    * LoginGUIdemox.java
    * Created on 29 November 2002, 18:59
    * @author  administrator
    import java.beans.*;
    public class LoginGUIdemo extends javax.swing.JFrame {
        private String userAction;
        private PropertyChangeSupport pcs;
        /** Creates new form LoginGUIdemox */
        // Note that in the full code there are setters and getters to allow access to the
        // components in the screen. For clarity they are not included here
        public LoginGUIdemo() {
            pcs = new PropertyChangeSupport(this);
            userAction = "";
            initComponents();
        public void setUserAction(String s) {
            userAction = s;
            pcs.firePropertyChange("userAction",null,userAction);
        public void addPropertyChangeListener(PropertyChangeListener l) {
            pcs.addPropertyChangeListener(l);
        public void removePropertyChangeListener(PropertyChangeListener l) {
            pcs.removePropertyChangeListener(l);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jComboBox1 = new javax.swing.JComboBox();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            getContentPane().setLayout(new java.awt.FlowLayout());
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jTextField1.setText("userid");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField1);
            jTextField2.setText("password");
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField2);
            jComboBox1.setToolTipText("Select Locale");
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    LocaleActionPerformed(evt);
            getContentPane().add(jComboBox1);
            jButton1.setText("Enter");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton2.setText("Cancel");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    CancelActionPerformed(evt);
            getContentPane().add(jButton2);
            pack();
        private void LocaleActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("LocaleChange");
        private void CancelActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Cancelled");
        private void EnterActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Submitted");
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new LoginGUIdemo().show();
        // Variables declaration - do not modify
        private javax.swing.JTextField jTextField2;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton1;
        // End of variables declaration

Maybe you are looking for