MVC风格
MVC风格
§模型-视图-控制器风格常被简称为MVC风格
§组件:模型、视图、控制器
§连接件:显式调用、隐式调用、其它机制(比如:Http协议)
工作机制:
Model:
§模型的职责
–负责数据存取
–负责业务逻辑实现
–负责数据验证
§模型:模型是应用程序的核心。
它封装内核数据与状态,对模型的改动将扩散到全部视图中。
全部须要从模型获取信息的对象都必须注冊为模型的视图。
§在事件驱动系统,当信息发生改变,模型通知观察者(observers) (一般是视图),从而引起视图反应。
View:
§视图的职责:
–获取用户输入
–向controller发送处理请求
–接收来自Controller的反馈
–将model的处理结果显示给用户
§一个model可能有多个View
Controller:
§控制器职责:
–接收来自客户的请求
–调用model运行
–调用View显示运行结果
§控制器:控制器是提供给用户进行操作的接口。每一个视图与一个控制器组件相关联。控制器接收用户的输入,一般是鼠标移动、键盘输入等。输入事件翻译成服务请求,送到模型或视图。用户仅仅通过控制器与系统交互。
§两个主要分离:
–模型与界面分离
–控制器与视图分离
§长处:
–将各方面问题分解开来考虑,简化了系统设计,保证了系统的可扩展性。
–改变界面不影响应用程序的功能内核,使得系统易于演化开发,可维护性好。
–同一信息能够有不同的展现方式。
–业务逻辑更易測试
程序:
模型类CarModel封装二手车软件的业务逻辑部分。包含核心数据以及tell()方法(将状态的改变通知视图类)
import java.io.*;
import java.net.URL;
import java.net.URI;
import javax.swing.*;
importjava.util.*;
public classCarModel{
private String[] carNameList;
privateURL imgURL;
privateURL carFileUrl;
privateImageIcon imgIcon;
private String carSelected;
private String bitPrice;
static final String CARFILES ="CarFiles/";
static final String CARIMAGES ="CarImages/";
public CarModel(){
carNameList=new String[200];
}
public void setCarList(String[] cars){
carNameList = cars;
}
public String[] getCarList(){
return carNameList;
}
public void setSelectedCar(String sCar){
carSelected = sCar;
}
publicString getSelectedCar(){
return carSelected;
}
publicvoid setBitPrice(String bPrice){
bitPrice = "";
bitPrice = bitPrice + bPrice;
}
public String getBitPrice(){
return bitPrice;
}
public void setupImageIcon(){
String iconStr = CARIMAGES + carSelected+".jpg";
imgIcon = createImageIcon(iconStr);
}
public ImageIcon getImageIcon(){
return imgIcon;
}
public void setCarFileURL(){
try{
String fileURLStr = CARFILES + carSelected+ ".html";
URI uri = (new File(fileURLStr)).toURI();
carFileUrl= uri.toURL();
}
catch (IOException e){
e.printStackTrace();
}
}
public URL getCarFileURL(){
return carFileUrl;
}
protected ImageIcon createImageIcon(Stringpath){
imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn'tfind file: " + path);
return null;
}
}
public void tell(View view){
view.update();
}
} // End ofclass
视图类CararGUIView和CarBitView为图形界面类,在update()方法中自己主动调用CarModel类的有关信息。并显示在图形界面上。
public interface View{
publicabstract void update();
}
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
import java.awt.event.*;
import com.sun.java.swing.plaf.windows.*;
public classCarGUIView extends JFrame implements View{
private JEditorPane editorPane;
private JScrollPane imagePane;
private JScrollPane textPane;
private JSplitPane splitPane;
private JLabel imgLabel;
private CarModel model;
public CarGUIView(CarModel cmodel){
super("Car information- Observer1");
model = cmodel;
buildUpScrollGUI();
}
private void buildUpScrollGUI(){
imgLabel = new JLabel();
imgLabel.setBackground(Color.green);
imgLabel.setMinimumSize(new Dimension(250, 200));
editorPane = new JEditorPane();
editorPane.setEditable(false);
imagePane = new JScrollPane(imgLabel);
imagePane.getViewport().setBackground(Color.green);
textPane = new JScrollPane(editorPane);
textPane.setMinimumSize(new Dimension(250, 200));
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setLeftComponent(imagePane);
splitPane.setRightComponent(textPane);
Dimension minimumSize = new Dimension(130, 100);
imagePane.setMinimumSize(minimumSize);
textPane.setMinimumSize(new Dimension(100, 100));
splitPane.setDividerLocation(160);
splitPane.setPreferredSize(new Dimension(500, 300));
Container contentPane = getContentPane();
contentPane.add(splitPane);
setSize(400, 150);
setVisible(true);
}
public void update(){
try{
URL url = model.getCarFileURL();
editorPane.setPage(url);
System.out.println("We have beencalled.");
}
catch (IOException e){
e.printStackTrace();
}
ImageIcon imIcon = model.getImageIcon();
imgLabel.setIcon(imIcon);
imgLabel.validate();
}
}
import java.awt.*;
importjavax.swing.*;
public classCarBitView extends JFrame implements View{
private JPanel showPanel;
private JLabel bitOfferedLabel;
private JTextArea bitText;
private CarModel model;
//public CarBitView(CarModel cmodel) throwsException{
public CarBitView(CarModel cmodel) {
super("Car Bit Info View- Observer2");
model = cmodel;
bitOfferedLabel = newJLabel("Latest bit offered:");
bitText = new JTextArea(4, 20);
bitText.setFont(newFont("Serif", Font.PLAIN, 14));
bitText.setLineWrap(true);
bitText.setWrapStyleWord(true);
Container contentPane =getContentPane();
contentPane.add(bitOfferedLabel,BorderLayout.NORTH);
contentPane.add(bitText,BorderLayout.CENTER);
setSize(400, 150);
setVisible(true);
}
public void update(){
System.out.println("Car bit hasbeen called.");
String sCar= model.getSelectedCar();
String pr = model.getBitPrice();
bitText.append("\n Bit price for"+ sCar + "="+ pr);
}
}// end ofclass
控制器Controller负责依据CarAuctionGUI对象输入的客户选择信息更新CarModel的数据。
importjava.awt.event.*;
importjavax.swing.*;
importjava.net.URL;
classController implements ActionListener{
private CarAuctionGUI objCarGui;
private CarModel cm;
private CarGUIView civ;
private CarBitView cb;
private String carPrice;
private String[] carList;
public Controller(CarAuctionGUIobjCarGui,CarModel cm,
CarGUIView civ,CarBitViewcb){
this.objCarGui = objCarGui;
this.cm=cm;
this.civ=civ;
this.cb=cb;
carList = objCarGui.getCarList();
cm.setCarList(carList);
}
public void actionPerformed(ActionEvent e){
String searchResult = null;
if(e.getActionCommand().equals(CarAuctionGUI.EXIT)){
System.exit(1);
}
if(e.getActionCommand().equals(CarAuctionGUI.SEARCH)){
String selectedCar =objCarGui.getSelectedCar();
cm.setSelectedCar(selectedCar);
cm.setCarFileURL();
cm.setupImageIcon();
cm.tell(civ);
}
if(e.getActionCommand().equals(CarAuctionGUI.BIT)){
carPrice = objCarGui.getBitPrice();
cm.setBitPrice(carPrice);
cm.tell(cb);
}
}
} // End ofclass Controller
importjava.awt.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
import java.awt.event.*;
import com.sun.java.swing.plaf.windows.*;
public classCarAuctionGUI extends JPanel {
private JTextField bitInputText;
private JLabel lblCarModel;
private JPanel buttonPanel;
private String[] carList;
private JComboBox cmbCarList;
private static CarModel cm;
private static CarGUIView civ;
private static CarBitView cb;
public static final String SEARCH ="Search";
public static final String BIT ="Bit";
public static final String EXIT ="Exit";
public CarAuctionGUI(){
super(new GridLayout(1,0));
setUpGUI();
}
private void setUpGUI(){
cmbCarList = new JComboBox();
String[] cl = getCarList();
setUpCarList(cl);
lblCarModel = new JLabel("Cars on auction:");
//Create the open button
JButton srchButton = new JButton(SEARCH);
srchButton.setMnemonic(KeyEvent.VK_S);
JButton exitButton = new JButton(EXIT);
exitButton.setMnemonic(KeyEvent.VK_X);
JButton bitButton = new JButton(BIT);
bitButton.setMnemonic(KeyEvent.VK_X);
bitInputText = new JTextField("Offeryour bit price",12);
buttonPanel = new JPanel();
//****************************************************
GridBagLayout gridbag = newGridBagLayout();
buttonPanel.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
buttonPanel.add(lblCarModel);
buttonPanel.add(cmbCarList);
buttonPanel.add(srchButton);
buttonPanel.add(bitButton);
buttonPanel.add(exitButton);
buttonPanel.add(bitInputText);
gbc.insets.top = 5;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.anchor = GridBagConstraints.EAST;
gbc.gridx = 0;
gbc.gridy = 0;
gridbag.setConstraints(lblCarModel, gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 1;
gbc.gridy = 0;
gridbag.setConstraints(cmbCarList, gbc);
gbc.anchor = GridBagConstraints.EAST;
gbc.insets.left = 2;
gbc.insets.right = 2;
gbc.insets.top = 25;
gbc.anchor = GridBagConstraints.EAST;
gbc.gridx = 0;
gbc.gridy = 3;
gridbag.setConstraints(srchButton, gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 1;
gbc.gridy = 3;
gridbag.setConstraints(exitButton, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
gridbag.setConstraints(bitButton, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gridbag.setConstraints(bitInputText,gbc);
Controller objButtonHandler = newController(this,cm,civ,cb);
srchButton.addActionListener(objButtonHandler);
exitButton.addActionListener(objButtonHandler);
bitButton.addActionListener(objButtonHandler);
add(buttonPanel);
setSize(new Dimension(800, 450));
setVisible(true);
}
public String getSelectedCar() {
return (String) cmbCarList.getSelectedItem();
}
public String getBitPrice(){
return bitInputText.getText();
}
// get the names of all the .html filesin a directory
public String[] getCarList(){
File f = new File("CarFiles");
String [] fileNames = f.list();
for(int i=0; i<fileNames.length; i++ ){
int len = fileNames[i].length();
fileNames[i]=fileNames[i].substring(0,len-5);
}
return fileNames;
}
public void setUpCarList(String[]carList){
for(int k=0; k<carList.length; k++) {
cmbCarList.addItem(carList[k]);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("MVCpattern demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CarAuctionGUI newContentPane = newCarAuctionGUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
static public void main(String argv[]) {
javax.swing.SwingUtilities.invokeLater(newRunnable() {
public void run() {
cm = new CarModel();
civ= new CarGUIView(cm);
cb = new CarBitView(cm);
createAndShowGUI();
}
});
}
}
MVC风格的更多相关文章
- ASP.NET MVC概述
原文:http://www.asp.net/mvc/tutorials/older-versions/overview/asp-net-mvc-overview 这篇文章帮助你了解关于ASP.NET ...
- 点燃圣火! Ember.js 的初学者指南
现在,到处都可以看到复杂的 JavaScript 应用程序. 由于这些应用程序变得越来越复杂,一长串的 jQuery 回调语句,或者通过应用程序在各个点执行不同的函数调用,这些都变得无法再让人接受. ...
- jQuery Moblie 学习之page、button、theme、panel、listview、controlgroup、navbar等(一)
1.jQTouch jQTouch与jQuery Moblie十分相似,也是一个jQuery插件,同样也支持HTML页面标签驱动,实现移动设备视图切换效果.不同的是它是专为WebKit内核的浏览器打造 ...
- Python Web 开发的十个框架【转载】
Python 是一门动态.面向对象语言.其最初就是作为一门面向对象语言设计的,并且在后期又加入了一些更高级的特性.除了语言本身的设计目的之外,Python标准 库也是值得大家称赞的,Python甚至还 ...
- RESTful框架调研
背景 当前的开放服务平台发展趋势,是服务使用者变得多种多样,其中既有各种前端设备(台式机.手机等),又有各种后端服务器,因此必须有一个统一的机制,方便各种服务使用者和开放服务平台进行通信.为了更好的实 ...
- Asp.Net Web API 2第五课——Web API路由
Asp.Net Web API 导航 Asp.Net Web API第一课——入门 http://www.cnblogs.com/aehyok/p/3432158.html Asp.Net Web ...
- Web API路由
前言 本文描述了 ASP.NET Web API 如何将 HTTP 请求路由到控制器. 如果你熟悉Asp.Net MVC,Web API的路由与Asp.Net MVC的路由是非常类似的.这主要的区别就 ...
- python 第三方模块 转 https://github.com/masterpy/zwpy_lst
Chardet,字符编码探测器,可以自动检测文本.网页.xml的编码. colorama,主要用来给文本添加各种颜色,并且非常简单易用. Prettytable,主要用于在终端或浏览器端构建格式化的输 ...
- Web API初印象
理解REST,RESTful和Web API 1.REST:Representational State Transfer表征状态转移,是Roy Fielding博士在2000年他的博士论文中提出来的 ...
随机推荐
- java web 学习五(servlet开发1)
一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...
- SQL知识累积
详细介绍select的文章,展示原始数据.SQL.查询结果,以及在不同数据库下SQL应该如何写. https://en.wikipedia.org/wiki/Select_(SQL) 目录如下: Co ...
- Source Insight中文乱码
搜索都是c++的代码,本来想下一个Vc,想了下,决定下个eclipse for C++,anyway,n次n久时间下载失败后,我接受了推荐,先下了个Source Insight来看代码.然后问题就出现 ...
- XTUOJ1247 Pair-Pair 预处理+暴力
分析:开个1000*1000的数组,预处理矩阵和,然后分类讨论就好 时间复杂度:O(n) #include <cstdio> #include <iostream> #incl ...
- 最小化安装CentOS7 + xfce4 +PHP + nginx +mariadb 开发环境
虚拟机自定义最小化安装,新增用户做为管理员,打开自动获取网络,桥接模式.所有的操作只有命令,不做解释,看不明白的可以自行搜索相关的资料. # 开头的行是注释行,# 开头的空行,我自己装机时做了快照.未 ...
- 圆内,求离圆心最远的整数点 hiho一下第111周 Farthest Point
// 圆内,求离圆心最远的整数点 hiho一下第111周 Farthest Point // 思路:直接暴力绝对T // 先确定x范围,每个x范围内,离圆心最远的点一定是y轴两端的点.枚举x的范围,再 ...
- POJ 2280&&hdu 1661
题意:给定平面上的N个点,属性分别标记为0和1,然后找一条直线,直线上的点全部溶解,一侧的1溶解,另一侧的0溶解.求出最多能溶解的点的个数. 思路:暴力枚举每个点,扫描线旋转.先做优化,如果一侧溶解0 ...
- ACM2050
问题描述: 平面上有n条折线,问这些折线最多能将平面分割成多少块? 样例输入 1 2 样例输出 2 7 答案是: 2n ( 2n + 1 ) / 2 + 1 - 2n = 2 n^2 – n + ...
- Spark系列(八)Worker工作原理
工作原理图 源代码分析 包名:org.apache.spark.deploy.worker 启动driver入口点:registerWithMaster方法中的case LaunchDriver ...
- java 中 正则 正则表达式 匹配 url
不多说 [http|https]+[://]+[0-9A-Za-z:/[-]_#[?][=][.][&]]* 这个就是匹配 网络上的网址 又称 url . 最起码 绝大部分的taobao ur ...