您的位置:首页 > 编程语言 > Java开发

读书笔记_java设计模式深入研究 第八章 状态模式 State

2014-12-29 10:21 721 查看
1,状态模式:事务有n个状态,且维护状态变化。

2,UML模型:





-1,上下文环境Context:定义客户程序需要的接口并维护一个具体状态角色的实例,将与状态相关的操作委托给当前的ConcreteState对象来处理。

-2,抽象状态State:定义接口以封装上下文环境的一个特定状态的行为。

-3,具体状态ConcreteState:具体状态。

3,简单代码:

packagepattern.chp08.state.simple;
/**
*类描述:状态抽象接口
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201410:44:21AMJingCreated.
*
*/
publicinterfaceIState{
/**
*
*方法说明:状态更改
*
*Author:Jing
*CreateDate:Dec26,201410:44:44AM
*
*@returnvoid
*/
voidgoState();
}
[/code]

packagepattern.chp08.state.simple;
/**
*类描述:状态B
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201410:50:24AMJingCreated.
*
*/
publicclassConcreteStateBimplementsIState{
publicvoidgoState(){
System.out.println("ConcreteStateB");
}
}
[/code]

packagepattern.chp08.state.simple;
/**
*类描述:状态A
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201410:50:04AMJingCreated.
*
*/
publicclassConcreteStateAimplementsIState{
publicvoidgoState(){
System.out.println("ConcreteStateA");
}
}
[/code]

packagepattern.chp08.state.simple;
/**
*类描述:上下文
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201410:52:03AMJingCreated.
*
*/
publicclassContext{
privateIStatestate;
publicvoidsetState(IStatestate){
this.state=state;
}
/**
*
*方法说明:根据条件选择某种状态
*
*Author:Jing
*CreateDate:Dec26,201410:52:51AM
*
*@returnvoid
*/
publicvoidmanage(){
state.goState();
}
}
[/code]

4,深入理解状态模式

-1,利用上下文类控制状态

手机应用,假设手机功能有存款和打电话,状态有正常、透支、停机。使用状态模式模拟:

packagepattern.chp08.state.cellState;
/**
*类描述:手机状态接口
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201411:04:09AMJingCreated.
*
*/
publicinterfaceICellState{
/**
*正常状态
*/
publicfloatNORMAL_LIMIT=0;
/**
*停机状态
*/
publicfloatSTOP_LIMIT=-1;
/**
*话费标准
*/
publicfloatCOST_MINUTE=0.20F;
/**
*
*方法说明:电话
*
*Author:Jing
*CreateDate:Dec26,201411:21:01AM
*
*@paramct
*@return
*@returnboolean
*/
booleanphone(CellContextct);
}
[/code]

packagepattern.chp08.state.cellState;
/**
*类描述:正常状态
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201411:35:54AMJingCreated.
*
*/
publicclassNormalStateimplementsICellState{
publicbooleanphone(CellContextct){
System.out.println(ct.name+":处于正常状态");
intminute=(int)(Math.random()*10+1);//随机产生打电话分钟数
ct.cost(minute);
//somesavecode
returnfalse;
}
}
[/code]

packagepattern.chp08.state.cellState;
/**
*类描述:透支状态下电话类
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201411:36:47AMJingCreated.
*
*/
publicclassOverDrawStateimplementsICellState{
publicbooleanphone(CellContextct){
System.out.println(ct.name+":处于透支状态");
intminute=(int)(Math.random()*10+1);//随机产生打电话分钟数
ct.cost(minute);
//somesavecode
returnfalse;
}
}
[/code]

packagepattern.chp08.state.cellState;
/**
*类描述:停机状态
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201411:36:23AMJingCreated.
*
*/
publicclassStopStateimplementsICellState{
publicbooleanphone(CellContextct){
System.out.println(ct.name+":处于停机状态");
returnfalse;
}
}
[/code]

packagepattern.chp08.state.cellState;
/**
*类描述:手机上下文状态类
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,201411:30:09AMJingCreated.
*
*/
publicclassCellContext{
StringstrPhone;//电话号码
Stringname;//姓名
floatprice;//金额
publicCellContext(StringstrPhone,Stringname,floatprice){
this.strPhone=strPhone;
this.name=name;
this.price=price;
}
/**
*
*方法说明:手机存钱
*
*Author:Jing
*CreateDate:Dec26,201411:31:41AM
*
*@paramprice
*@returnvoid
*/
publicvoidsave(floatprice){
this.price+=price;
}
/**
*
*方法说明:手机话费
*
*Author:Jing
*CreateDate:Dec26,201411:32:13AM
*
*@paramminute
*@returnvoid
*/
publicvoidcost(intminute){
this.price-=ICellState.COST_MINUTE*minute;
}
/**
*
*方法说明:获取不同手机状态
*
*Author:Jing
*CreateDate:Dec26,201411:33:15AM
*
*@return
*@returnboolean
*/
publicbooleancall(){
ICellStatestate=null;
if(price>ICellState.NORMAL_LIMIT){
state=newNormalState();
}elseif(price<ICellState.STOP_LIMIT){
state=newStopState();
}else{
state=newOverDrawState();
}
state.phone(this);
returntrue;
}
}
[/code]

/**
*类描述:
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20142:25:14PMJingCreated.
*
*/
publicclassTest{
publicstaticvoidmain(String[]args){
CellContextc=newCellContext("213130","LaoLiu",1);
c.call();
c.call();
}
}
[/code]

5,应用探索

计算机内存监控

packagepattern.chp08.state.ctrl;
importjava.awt.Container;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JComponent;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
/**
*类描述:参数控制面板
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20142:35:38PMJingCreated.
*
*/
publicclassCtrlPanelextendsJPanel{
privatestaticfinallongserialVersionUID=-6539318368246202726L;
JComponent[]c={newJTextField(4),newJTextField(4),newJButton("开始检测"),
newJButton("停止检测")};
booleanbmark[][]={{true,true,true,false},{false,false,false,true}};
ActionListenerstartAct=newActionListener(){//开始检测按钮响应事件
publicvoidactionPerformed(ActionEvente){
setState(1);//设置组件为初始状态
inthigh=Integer.parseInt(((JTextField)c[0]).getText());
intlow=Integer.parseInt(((JTextField)c[1]).getText());
Containerc=CtrlPanel.this.getParent();
StringclassName=c.getClass().getName();
while(!"pattern.chp08.state.ctrl.MyFrame".equalsIgnoreCase(className)){
c=c.getParent();
className=c.getClass().getName();
}
((MyFrame)c).startMonitor(high,low);
}
};
ActionListenerstopAct=newActionListener(){//停止检测按钮响应
publicvoidactionPerformed(ActionEvente){
setState(0);
Containerc=CtrlPanel.this.getParent();
StringclassName=c.getClass().getName();
while(!"pattern.chp08.state.ctrl.MyFrame".equalsIgnoreCase(className)){
c=c.getParent();
className=c.getClass().getName();
}
((MyFrame)c).stopMonitor();
}
};
publicCtrlPanel(){
add(newJLabel("优良"));
add(c[0]);
add(newJLabel("良好"));
add(c[1]);
add(c[2]);
add(c[3]);
setState(0);//设置初始
((JButton)c[2]).addActionListener(startAct);
((JButton)c[3]).addActionListener(stopAct);
}
/**
*
*方法说明:设置按钮状态
*
*Author:JingCreateDate:Dec26,20142:42:17PM
*
*@paramnState
*@returnvoid
*/
voidsetState(intnState){
for(inti=0;i<bmark[nState].length;i++){
c[i].setEnabled(bmark[nState][i]);
}
}
}
[/code]

packagepattern.chp08.state.ctrl;
importjavax.swing.Box;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.border.BevelBorder;
/**
*类描述:中间数值展示面板类
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20143:02:21PMJingCreated.
*
*/
publicclassContentPanelextendsJPanel{
privatestaticfinallongserialVersionUID=3347768107958337339L;
JTextFieldtotalField=newJTextField(20);//总内存展示
JTextFieldfreeField=newJTextField(20);//空闲内存显示
JTextFieldratioField=newJTextField(20);//空闲率展示
@SuppressWarnings("static-access")
publicContentPanel(){
totalField.setEditable(false);
freeField.setEditable(false);
ratioField.setEditable(false);
Boxb1=Box.createVerticalBox();
b1.add(newJLabel("总内存:"));
b1.add(b1.createVerticalStrut(16));
b1.add(newJLabel("空闲内存:"));
b1.add(b1.createVerticalStrut(16));
b1.add(newJLabel("所占比例:"));
b1.add(b1.createVerticalStrut(16));
Boxb2=Box.createVerticalBox();
b2.add(totalField);
b2.add(b2.createVerticalStrut(16));
b2.add(freeField);
b2.add(b2.createVerticalStrut(16));
b2.add(ratioField);
b2.add(b2.createVerticalStrut(16));
add(b1);
add(b2);
setBorder(newBevelBorder(BevelBorder.RAISED));
}
/**
*
*方法说明:设置对应Field值
*
*Author:Jing
*CreateDate:Dec26,20143:11:22PM
*
*@paramvalue
*@paramfree
*@paramratio
*@returnvoid
*/
voidsetValue(longvalue,longfree,longratio){
totalField.setText(value+"M");
freeField.setText(free+"M");
ratioField.setText(ratio+"%");
}
}
[/code]

packagepattern.chp08.state.ctrl;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
/**
*类描述:上下文类
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20143:24:15PMJingCreated.
*
*/
publicclassStatePanelextendsJPanel{
privatestaticfinallongserialVersionUID=1L;
JTextFieldtxtInfo=newJTextField(4);
JTextFieldtxtHour=newJTextField(10);
IStatestate;
intmark=-1;
publicStatePanel(){
add(newJLabel("当前内存状态:"));
add(txtInfo);
add(newJLabel("持续时间:"));
add(txtHour);
txtInfo.setEnabled(false);
txtHour.setEnabled(false);
}
/*
*设置内存状态
*/
publicvoidsetState(intmark){
if(this.mark==mark){//内存无变化
return;
}
this.mark=mark;
switch(mark){
case1:
state=newHighState();
break;
case2:
state=newMidState();
break;
case3:
state=newLowState();
break;
}
}
/**
*
*方法说明:设置对应值
*
*Author:JingCreateDate:Dec26,20143:31:39PM
*
*@returnvoid
*/
publicvoidprocess(){
txtInfo.setText(state.getStateInfo());
intsize=state.getStateInterval();
//DecimalFormatdf=newDecimalFormat("0.00");
txtHour.setText(""+/*df.format((float)size/3600)*/size+"S");
}
}
[/code]

packagepattern.chp08.state.ctrl;
/**
*类描述:状态接口
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20143:17:18PMJingCreated.
*
*/
publicinterfaceIState{
/**
*
*方法说明:获取状态信息
*
*Author:JingCreateDate:Dec26,20143:17:45PM
*
*@return
*@returnString
*/
StringgetStateInfo();
/**
*
*方法说明:获取统计频率
*
*Author:JingCreateDate:Dec26,20143:18:12PM
*
*@return
*@returnint
*/
intgetStateInterval();
}
[/code]

packagepattern.chp08.state.ctrl;
/**
*类描述:内存紧张
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20143:19:28PMJingCreated.
*
*/
publicclassLowStateimplementsIState{
privateinttimes;
publicStringgetStateInfo(){
//someothercode
//此处可设置通知管理员等其他代码
return"一般";
}
publicintgetStateInterval(){
returntimes++;
}
}
[/code]

packagepattern.chp08.state.ctrl;
/**
*类描述:内存充足
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20143:18:56PMJingCreated.
*
*/
publicclassHighStateimplementsIState{
privateinttimes;
publicStringgetStateInfo(){
//someothercode
//此处可设置通知管理员等其他代码
return"充足";
}
publicintgetStateInterval(){
returntimes++;
}
}
[/code]

packagepattern.chp08.state.ctrl;
/**
*类描述:内存良好
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20143:19:12PMJingCreated.
*
*/
publicclassMidStateimplementsIState{
privateinttimes;
publicStringgetStateInfo(){
//someothercode
//此处可设置通知管理员等其他代码
return"良好";
}
publicintgetStateInterval(){
returntimes++;
}
}
[/code]

packagepattern.chp08.state.ctrl;
importjava.awt.BorderLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JFrame;
importjavax.swing.Timer;
importsun.management.ManagementFactory;
importcom.sun.management.OperatingSystemMXBean;
/**
*类描述:主窗口
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20143:47:44PMJingCreated.
*
*/
publicclassMyFrameextendsJFrameimplementsActionListener{
privatestaticfinallongserialVersionUID=1L;
CtrlPanelctrlPanel=newCtrlPanel();//参数面板
ContentPanelcontentPanel=newContentPanel();//数值显示面板
StatePanelstatePanel=newStatePanel();//状态面板
Timertimer=newTimer(1000,this);//定时器
inthigh,mid;
/**
*
*方法说明:初始化
*
*Author:JingCreateDate:Dec26,20143:51:54PM
*
*@returnvoid
*/
publicvoidinit(){
add(ctrlPanel,BorderLayout.NORTH);
add(contentPanel,BorderLayout.CENTER);
add(statePanel,BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,220);
setVisible(true);
}
/**
*
*方法说明:启动自动检测
*
*Author:JingCreateDate:Dec26,20143:53:53PM
*
*@paramhigh
*@parammid
*@returnvoid
*/
publicvoidstartMonitor(inthigh,intmid){
this.high=high;
this.mid=mid;
timer.start();
}
/**
*
*方法说明:停止检测
*
*Author:JingCreateDate:Dec26,20143:54:51PM
*
*@returnvoid
*/
publicvoidstopMonitor(){
timer.stop();
}
publicvoidactionPerformed(ActionEvente){//定时器响应方法
OperatingSystemMXBeanosmxb=(OperatingSystemMXBean)ManagementFactory
.getOperatingSystemMXBean();
longtotal=osmxb.getTotalPhysicalMemorySize();
longfree=osmxb.getFreePhysicalMemorySize();
intratio=(int)(free*100L/total);
contentPanel.setValue(total/(1024*1024),free/(1024*1024),ratio);
intmark=-1;
if(ratio>=high){
mark=1;
}elseif(ratio<mid){
mark=3;
}else{
mark=2;
}
statePanel.setState(mark);
statePanel.process();
}
}
[/code]

packagepattern.chp08.state.ctrl;
/**
*类描述:
*
*@author:Jing
*@version$Id:Exp$
*
*History:Dec26,20144:02:27PMJingCreated.
*
*/
publicclassTest{
publicstaticvoidmain(String[]args){
newMyFrame().init();
}
}
[/code]

运行界面:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: