Friday, January 13, 2012

Model-View-Controller (MVC) pattern simple example

About this architectural pattern is so much articles have been written, so I don't describe it in details. Follow MVC in Wikipedia link to read about theory of MVC. I just want to represent a very simple implementation of MVC pattern using Java and Swing library. 
The MVC block diagram is shown on Fig.1.


Fig.1

Model
Our simple model just has a one private variable "x". This variable is initialized to zero by default constructor Model(), or to custom value by constructor Model(int x) . Methods incX() and getX() give access to "x". Method incX() performs some operations: it increments "x", while method getX just return "x". Note that Model don't know anything about View and Controller.
package mvc.models;

public class Model {
    
    private int x;
    
    public Model(){
        x = 0;
    }
    
    public Model(int x){
        this.x = x;
    }
    
    public void incX(){
        x++;
    }
    
    public int getX(){
        return x;
    }
}

View
The View class uses Swing library to create window and place label and button on it. Public method setText(String text) allows us to set text label, method getButton() returns button reference. Note that View don't know anything about Model and Controller.
package mvc.views;

import javax.swing.*;
import java.awt.BorderLayout;

public class View {
      
    private JFrame frame;
    private JLabel label;
    private JButton button;

    
    public View(String text){
        frame = new JFrame("View");                                    
        frame.getContentPane().setLayout(new BorderLayout());                                          
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           
        frame.setSize(200,200);        
        frame.setVisible(true);
        
        label = new JLabel(text);
        frame.getContentPane().add(label, BorderLayout.CENTER);
        
        button = new JButton("Button");        
        frame.getContentPane().add(button, BorderLayout.SOUTH);        
    }
        
    public JButton getButton(){
        return button;
    }
    
    public void setText(String text){
        label.setText(text);
    }
    
    
}

Controller

The Controller class keeps references to Model and View classes. So Controller sees Model and View interfaces. Controller provides interaction between Model and View. Method control() gets reference to view's button and assign actionListener to it. In actionListener's method actionPerformed() method linkBtnAndLabel() is called. In linkBtnAndLabel() model's variable "x" increments and than "x" sends to view's label to display changes.
package mvc.controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import mvc.models.*;
import mvc.views.*;

public class Controller {

    private Model model;
    private View view;
    private ActionListener actionListener;
    
    public Controller(Model model, View view){
        this.model = model;
        this.view = view;
                          
    }
    
    public void contol(){        
        actionListener = new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {                  
                  linkBtnAndLabel();
              }
        };                
        view.getButton().addActionListener(actionListener);   
    }
    
    private void linkBtnAndLabel(){
        model.incX();                
        view.setText(Integer.toString(model.getX()));
    }    
}

Main class

The Main class creates objects of Model, View and Controller classes, initializes Controller by Model and View and call Controller's method control(). The result by compiling and run program is showed on Fig.2.
package mvc;

import javax.swing.SwingUtilities;

import mvc.models.*;
import mvc.views.*;
import mvc.controllers.*;

public class Main
{
    public static void main(String[] args) {           
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {                                           
                Model model = new Model(0);
                View view = new View("-"); 
                Controller controller = new Controller(model,view);
                controller.contol();
            }
        });  
    }
}

Why MVC?

Perhaps this example is too simple to understand why MVC is needed. But the power of MVC arises in complicated and large programs. MVC helps to divide functionality between different objects, so program becomes more clear and understandable. The pattern allows to modify code (realization), that is encapsulated inside one of these classes without intrusion inside other classes code(of course you have to keep the same interfaces).

142 comments:

  1. Great article. I spent a lot of time trying to find some simple code that I could use to view how this model works. Great example, thanks!

    ReplyDelete
  2. Very useful Code as me as freshers

    Nathan Ramesh

    ReplyDelete
  3. Very very Helpful Example

    Thank you

    ReplyDelete
  4. Great blogpost!!

    Just wrote my first MVC code; with the help of your example.

    Thanks.

    ReplyDelete
  5. Very good example for MVC pattern ....

    Thanks

    ReplyDelete
  6. amazingly helpful. thanks.

    ReplyDelete
  7. Hi, how do I call another controller action from let's say a menu action ?

    ReplyDelete
    Replies
    1. Hello,
      The another controller action could be added in the following way, for example:

      1) In "View" class add menu-related properties:
      private JMenuBar menuBar;
      private JMenu menu;
      private JMenuItem menuItem;

      2) Then in "View" class constructior add several lines to create menu and menuItem
      and assign menu to the frame:
      menuBar = new JMenuBar();//Create the menu bar.
      menu = new JMenu("SimpleMenu");//Create the menu
      menuBar.add(menu); //add menu to menuBar
      menuItem = new JMenuItem("MenuButton"); //create menuItem
      menu.add(menuItem); //add menuIten to the menu
      frame.setJMenuBar(menuBar); //set menuBar to frame

      3) In "View" class add method to get access to the menu:
      public JMenuBar getMenuBar(){
      return menuBar;
      }

      4) In "Controller" class in "control" method add a one line of code to add action to menuItem:
      view.getMenuBar().getMenu(0).getItem(0).addActionListener(actionListener);

      Delete
  8. Hello Dmitry,
    I ve tried your guidance from point 1 to 4. but i get error on point 3 because getMenuBar is method in JFrame. My quick solution is to change getMenuBar to getMnuBar. but I'm not satisfy with this way. maybe you have another solution suppose that overriding getMenuBar method? if it is true how to overriding getMenuBar method?

    ReplyDelete
    Replies
    1. Hello,
      In my example the "View" class contains "JFrame" class instance as property (uses composition) but is not inherited from it. That's why there is no conflict of "getMenuBar" method name. It seems that in your case, as I've understood, you "View" class is inherited from "JFrame" class that's why the name conflict occures. Then the renaming of method helps. It's hard to say what is the best way, it depends... As I know in Object-oriented approach the composition is preffered to inheritance (it gives more flexibility), and if inheritance is occured it should be done from interface... My advice is to change ihneritance to composition and left "getMenuBar"... but it is just an advice :)

      Delete
  9. This comment has been removed by the author.

    ReplyDelete
  10. yes your advice is well done thank u

    ReplyDelete
  11. Thanks! your artical is crisp and clean as it should be for new learners like me. For more than a week I was confused how I am going to implement MVC for Swing UI without Spring framework. I really got the confidence now to start my implementation. Thanks once again! Please keep posting such simple and powerful articles.

    ReplyDelete
  12. Superb explanation. thanks u

    ReplyDelete
  13. This article actually helped me a lot.. Thanks!

    ReplyDelete
  14. Thank you very much Dmitry. You wrote in very basic and it is very understandable.

    ReplyDelete
  15. Thank you for a simple example and a clear description. Though I've done it before using a framework, only now I get the nuts and bolts of MVC. Thank you!

    ReplyDelete
  16. thank you for the data which you have blogged ..hope this will definitely help our students to let them know and aware all the concepts which is related to this.

    ReplyDelete
  17. as a fresher who all wanted to go to selenium it would be really helpful for aware of basics and as well as for interviews.Amc Square Reviews

    ReplyDelete
  18. as a fresher who all wanted to go to selenium it would be really helpful for aware of basics and as well as for interviews
    Amc Square Reviews

    ReplyDelete
  19. I need that, but using date column with mysql, any idea, thank you a lot

    ReplyDelete
  20. I need that, but using date column with mysql, any idea, thank you a lot

    ReplyDelete
  21. Is there a tool to directly draw these diagrams. Cna creately help?

    ReplyDelete
  22. i am very happy,because my problem has been solved this example for MVC models ,special thanks sir

    ReplyDelete
  23. i am very happy,because my problem has been solved this example for MVC models ,special thanks sir

    ReplyDelete
  24. thanks a lot !!!! this the best easiest example for using MVC with Java . all my respect !!!

    ReplyDelete
  25. thanks for give the concept of swing with mvc

    ReplyDelete
  26. thanks for give the concept of swing with mvc

    ReplyDelete
  27. Thanks. Just a small request, can you try to have the same code written with MVP to understand how it differs from the MVC?

    ReplyDelete
  28. Thank you, I think this example is easy to understand

    ReplyDelete
  29. This is exatly what I was looking for

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. This is a Model View Presenter (MVP) variant, not Model View Controller (MVC).

    ReplyDelete
    Replies
    1. I agree with Mart. This is MVP not MVC

      Delete
    2. I agree with Mart. This is MVP not MVC

      Delete
  32. Thanks. Your sample was very useful to me

    ReplyDelete
  33. Thanks for this example. But now, how can I do if I want to put some text (from a database for example) in a jTextField ? I try but it doesn't work...
    Thanks a lot for your answer.

    ReplyDelete
  34. Thanks for sharing this article..

    ReplyDelete
  35. Thanks for the detailed explanation about Model View Controller, Very helpful to learn with this post. Cleared many doubts here. I'm sure this will surely help me with my AngularJS Certification Training.

    Thank You

    ReplyDelete
  36. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ..Best Angularjs Training in Chennai|Angularjs Training in Chennai

    ReplyDelete
  37. Excellent example for beginners on MVC pattern.. thank you very much Dmitry

    ReplyDelete
  38. I was handling an assignment in this topic and I did know how to solve the problem but after landing on this page all my problems were solved and I was able to follow the step by step procedure given to come up with an MVC pattern and I will only be in need of proofreading services which are available by clicking on Proofreading Website.

    ReplyDelete
  39. We this article content information very great.I'll be easy understood model view controller.We have to explain about model view controller very useful to me.
    Software Testing Training in Chennai | Software Testing Training in Chennai with Placement
    angularjs 2 training in chennai | best angularjs 2 training in chennai with placement

    ReplyDelete
  40. This comment has been removed by the author.

    ReplyDelete
  41. Excellent ! I am truly impressed that there is so much about this subject that has been revealed and you did it so nicely.
    Dot Net Training in Chennai

    ReplyDelete
  42. Thanks Dmitri,
    The best explanation I've seen of this concept

    ReplyDelete
  43. Thanks a lot very much for the high quality and results-oriented help.
    I won’t think twice to endorse your blog post to anybody who wants
    and needs support about this area.


    java training in chennai


    java training in bangalore

    ReplyDelete
  44. Ciitnoida provides Core and java training institute in

    noida
    . We have a team of experienced Java professionals who help our students learn Java with the help of Live Base Projects. The object-

    oriented, java training in noida , class-based build

    of Java has made it one of most popular programming languages and the demand of professionals with certification in Advance Java training is at an

    all-time high not just in India but foreign countries too.

    By helping our students understand the fundamentals and Advance concepts of Java, we prepare them for a successful programming career. With over 13

    years of sound experience, we have successfully trained hundreds of students in Noida and have been able to turn ourselves into an institute for best

    Java training in Noida.

    java training institute in noida
    java training in noida

    ReplyDelete
  45. Great post!This article gives more information, Thanks for sharing with us.

    Selenium Training in Chennai

    ReplyDelete
  46. Such devastating details shared by you. I am glad to learn this useful details from this blog, and I admire your efforts. Continue posting such relevant details and keep us updated.
    Web Design Company | Web development Lucknow

    ReplyDelete
  47. Awesome post. Really you are shared very informative concept... Thank you for sharing. Keep on updating...
    Python Training in Chennai | Python Training Institute in Chennai

    ReplyDelete
  48. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post I would like to read this
    java training in chennai | java training in bangalore

    java online training | java training in pune

    java training in chennai | java training in bangalore

    ReplyDelete
  49. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in Chennai | rpa training in pune

    rpa training in tambaram | rpa training in sholinganallur

    rpa training in Chennai | rpa training in velachery

    rpa online training | rpa training in bangalore

    ReplyDelete
  50. Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
    python training in tambaram
    python training in annanagar
    python training in Bangalore

    ReplyDelete
  51. Awesome post. Really you are shared very informative concept... Thank you for sharing. Keep on updating...
    Business Analysis Training

    Cognos Training

    DataScience Training

    DataStage Training

    ReplyDelete
  52. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    Sap Hana Training
    Sap Cs Training
    Sap Bw On Hana Training
    Sap Basis Training

    ReplyDelete
  53. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
    Golden Gate Selfplaced Videos

    Powershell Selfplaced Videos

    Dell Boomi Selfplaced Videos

    Hyperion Essabse Selfplaced Videos

    ReplyDelete
  54. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    Best Selenium Training in Chennai | Selenium Training Institute in Chennai | Besant Technologies

    Selenium Training in Bangalore | Best Selenium Training in Bangalore

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    ReplyDelete
  55. Thanks For sharing Your information The Information Shared Is Very Valuable Please Keep updating Us Time Just Went On Redaing The Article Python Online Course Devops Online Course Data Science Online Course Aws Science Online Course

    ReplyDelete
  56. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Microsoft Azure online training
    Selenium online training
    Java online training
    uipath online training
    Python online training

    ReplyDelete
  57. This is best one article so far I have read online, I would like to appreciate you for making it very simple and easy.

    lg mobile service chennai
    lg mobile repair
    lg mobile service center near me

    ReplyDelete
  58. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete

  59. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading Python classes in pune new articles. Keep up the good work!

    ReplyDelete
  60. I am really thankful for posting such useful information. It really made me understand lot of important concepts in the topic. Keep up the good work!
    Oracle Training in Chennai | Oracle Course in Chennai

    ReplyDelete
  61. Really Interesting Article . Nice information will look forwardr next article update Keep posting the articles :)
    If you are looking for any data science Related information please visit our website Data Science Course In Bangalore page!

    ReplyDelete
  62. Great Post. The information provided is of great use as I got to learn new things. Keep Blogging.Dell Boomi Training in Bangalore


    ReplyDelete
  63. Post is very useful. Thank you, this useful information.

    Became an Expert In Google Cloud Platform Training in Bangalore! Learn from experienced Trainers and get the knowledge to crack a coding interview, @Softgen Infotech Located in BTM Layout.

    ReplyDelete

  64. It is amazing to visit your site. Thanks for sharing this information, this is useful to me...
    UI Path Online Training
    UI Path Training in Hyderabad

    ReplyDelete
  65. The main motive of the Google Cloud Big Data Services is to spread the knowledge so that they can give more big data engineers to the world.

    ReplyDelete
  66. I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read !! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site.
    data science course in guwahati

    ReplyDelete
  67. We're offering additional discount on early enrollment on full module Automation Training. Get Job Support with Unlimited Placement Opportunities.
    Call us at +91-9953489987, 9711287737
    For more details Visit www.diac.co.in

    ReplyDelete
  68. It's actually a great and helpful piece of information. I am satisfied that you just shared this useful information for us. The Last Of Us 2 Ellie Jacket

    ReplyDelete
  69. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Salesforce Training in Pune

    ReplyDelete
  70. "Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Salesforce Training in Pune"

    ReplyDelete
  71. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Salesforce Training in Pune

    ReplyDelete
  72. very useful blog to learner so happy to be part in this blog. Thank you
    Data Science Online Training

    ReplyDelete
  73. I liked this article very much. The content is very good. Keep posting.
    Data Science Online Training

    ReplyDelete
  74. I really enjoyed reading this post, big fan. Keep up the good work and let me know when you can post more articles or where I can find out more on the topic

    Data science training
    Data Analytics Training
    Devops training
    Selenium training
    AWS Training courses and certification

    ReplyDelete
  75. This is Best MVC Examples You want to learn more...


    Online IT Software Courses Training ICT South Bopal - Ahmedabad, India

    Institute of Computer Training - ICT Bopal

    ReplyDelete
  76. software testing company in India
    software testing company in Hyderabad
    Thanks for providing such a great information about Model-View-Controller (MVC) pattern.
    It's an amazing to visit u r site.
    keep sharing.

    ReplyDelete
  77. This is best one article so far I have read online, I would like to appreciate you for making it very simple and easy.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  78. Nice Blog !
    Here We are Specialist in Manufacturing of Movies, Gaming, Casual, Faux Leather Jackets, Coats And Vests See Kayce Dutton Jacket

    ReplyDelete
  79. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    top blueprism online trainingI just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    top blueprism online training

    ReplyDelete
  80. Thank you for posting informative insights, I think we have got some more information to share with! Do check out
    oracle training in chennai and let us know your thoughts. Let’s have great learning!

    ReplyDelete
  81. Learn Oracle PLSQL Training in Chennai for excellent job opportunities from Infycle Technologies, the best Oracle Training Institute in Chennai. Infycle Technologies is the best & trustworthy software training center in Chennai, applies full hands-on practical training with professional trainers in the field. In addition to that, the mock placement interviews will be arranged by the alumni for the candidates, so that, they can meet the job interviews without missing them. For transforming your career to a higher level call 7502633633 to Infycle Technologies & grab a free demo session to know more.Oracle PLSQL Training in Chennai | Infycle Technologies

    ReplyDelete
  82. Great Content. It will useful for knowledge seekers. Keep sharing your knowledge through this kind of article.
    MVC Training in Chennai
    MVC Classes in Chennai

    ReplyDelete
  83. This comment has been removed by the author.

    ReplyDelete
  84. Finish the Big Data Certification in Chennai from Infycle Technologies, the best software training institute in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Java, Hadoop, Selenium, Android, and iOS Development, etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.

    ReplyDelete
  85. very useful article.Technical contents are so good.Keep going
    Escort Service in Noida

    ReplyDelete
  86. Very useful article.Technical contents are so good.Keep going
    Escort Services in Gurgaon

    ReplyDelete
  87. Impressive! I finally found a great post here. Good article on Data Science. It is really a great experience to read your post. Thank you for sharing your innovative ideas with Our Vision.
    online flower shop
    orchid wedding bouquet
    sunflower wedding bouquet
    Wedding Flower Delivery
    wedding flowers near me
    orchid wedding bouquet
    cheap wedding flowers
    wedding bouquet flowers online
    wedding flowers order online
    wedding bouquets near me
    flower delivery Dublin
    flower delivery Dublin Ireland
    flower delivery Dublin
    flower delivery Dublin
    birthday flowers delivery Dublin
    same day birthday flower delivery
    flower shop Dublin
    birthday bouquet delivery Ireland
    send birthday flowers online Ireland
    same day birthday flower delivery Ireland
    next day birthday flower delivery Ireland
    birthday flowers delivery Ireland
    Send Birthday Flowers Ireland
    order birthday flowers online Ireland
    Birthday Flowers Ireland
    birthday flowers delivery near me

    ReplyDelete
  88. Impressive! I finally found a great post here. Good article on Data Science. It is really a great experience to read your post. Thank you for sharing your innovative ideas with Our Vision.
    online flower shop

    ReplyDelete
  89. Thanks for posting this info. I just want to let you know that I just check out your site. Adam Jensen Coat

    ReplyDelete
  90. Existing without the answers to the difficulties you’ve sorted out
    through this guide is a critical case, as well as the kind which could
    have badly affected my entire career if I had not discovered your
    website.
    oracle apps dba training in Chennai
    best java training institute in Chennai
    node js developer course in Chennai

    ReplyDelete
  91. This is really useful information, I really enjoyed reading this article CCSP certification

    ReplyDelete
  92. The idea is fantastic and the content is excellent, providing valuable information on various topics. Data science training in Hyderabad

    ReplyDelete