this is a simple attempt about implementing MVC pattern in Java. I was wondering if I'm in the right way because I need this for a Java college exam. This is a quick code that shows what I understood about the MVC way of work. Thanks to anyone who would comment this code.
- Is there a better way of determine data type other than instanceof or an enum+switch construct?
package exampleofuse;
import java.awt.Color;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class MVC {
/*
* Proof of concept for MVC pattern: theView, theModel and theController are meant to be different classes
* */
/*
* A wiew which main porpuse is to provide a dynamic visualization for
* data.
* data consist into a string for this example, so in the example I use JOptionPane
*
* NB:May be a JFrame with different JPanels created depending on data type
* */
public class theView
{
private final String aMessage = "The message in the view before the Content\n";
private final String errMsg = "Content not Supported";
JOptionPane theOPane;
public void showData(Object data)//data may be of different kinds, may be used an Enum class
{
if(data instanceof String)
JOptionPane.showMessageDialog(null, aMessage+data);
else
JOptionPane.showMessageDialog(null, aMessage+errMsg);
}
}
/*
* A Model that performs operations onto data received.
* In this case data is a String, and the operation is toUpperCase
* */
public class theModel
{
private final String errMsg = "Content not Supported";
public Object performOperation(Object data)//data may be of different kinds, may be used an Enum class
{
if(data instanceof String)
return ((String) data).toUpperCase();
return errMsg;
}
}
/*
* The Controller uses theModel to pass data to be visualized by theView
* */
public class theController
{
/*
* Best name choice EVER
* */
private theModel theModel;
private theView theView;
private Scanner in;
private final String prompt="Insert the String(Possibly lowercase)\n>>>";//but never trust user input right?
public theController()
{
this.theModel = new theModel();
this.theView = new theView();
this.in = new Scanner(System.in);
}
public void startController()
{
System.out.print(prompt);//This syso may be in the view as a log, but this is an example
theView.showData(theModel.performOperation(in.nextLine()));
}
public void startBrokenController()
{
theView.showData(new Color(5));//random object
}
public void startBrokenController1()
{
theView.showData(theModel.performOperation(new Color(5)));
}
}
public static void main(String[] args) {
MVC theMVCenclosingtype = new MVC();
theController theController = theMVCenclosingtype.new theController();
theController.startController();
theController.startBrokenController();
theController.startBrokenController1();
}
}
Aucun commentaire:
Enregistrer un commentaire