读书笔记_java设计模式深入研究 第八章 状态模式 State
生活随笔
收集整理的這篇文章主要介紹了
读书笔记_java设计模式深入研究 第八章 状态模式 State
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1,狀態模式:事務有n個狀態,且維護狀態變化。 2,UML模型:
-1,上下文環境Context:定義客戶程序需要的接口并維護一個具體狀態角色的實例,將與狀態相關的操作委托給當前的Concrete ?State對象來處理。 -2,抽象狀態State:定義接口以封裝上下文環境的一個特定狀態的行為。 -3,具體狀態ConcreteState:具體狀態。 3,簡單代碼:
?package pattern.chp08.state.simple;?/** * 類描述:狀態抽象接口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:44:21 AM Jing Created. * */public interface IState { /** * * 方法說明:狀態更改 * * Author: Jing * Create Date: Dec 26, 2014 10:44:44 AM * * @return void */ void goState();} package pattern.chp08.state.simple;?/** * 類描述:狀態B * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:50:24 AM Jing Created. * */public class ConcreteStateB implements IState{? public void goState() { System.out.println("ConcreteStateB"); }?} package pattern.chp08.state.simple;?/** * 類描述:狀態A * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:50:04 AM Jing Created. * */public class ConcreteStateA implements IState {? public void goState() { System.out.println("ConcreteStateA"); }?} package pattern.chp08.state.simple;?/** * 類描述:上下文 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:52:03 AM Jing Created. * */public class Context {? private IState state;? public void setState(IState state) { this.state = state; } /** * * 方法說明:根據條件選擇某種狀態 * * Author: Jing * Create Date: Dec 26, 2014 10:52:51 AM * * @return void */ public void manage(){ state.goState(); }} 4,深入理解狀態模式 -1,利用上下文類控制狀態 ? ??? ? 手機應用,假設手機功能有存款和打電話,狀態有正常、透支、停機。使用狀態模式模擬:
? ??
?package pattern.chp08.state.cellState;?/** * 類描述:手機狀態接口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:04:09 AM Jing Created. * */public interface ICellState { /** * 正常狀態 */ public float NORMAL_LIMIT = 0; /** * 停機狀態 */ public float STOP_LIMIT = -1; /** * 話費標準 */ public float COST_MINUTE = 0.20F; /** * * 方法說明:電話 * * Author: Jing * Create Date: Dec 26, 2014 11:21:01 AM * * @param ct * @return * @return boolean */ boolean phone(CellContext ct); } package pattern.chp08.state.cellState;?/** * 類描述:正常狀態 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:35:54 AM Jing Created. * */public class NormalState implements ICellState {? public boolean phone(CellContext ct) {? System.out.println(ct.name + ": 處于正常狀態");? int minute = (int) (Math.random() * 10 + 1);// 隨機產生打電話分鐘數 ct.cost(minute); //some save code return false; }?} package pattern.chp08.state.cellState;?/** * 類描述:透支狀態下電話類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:36:47 AM Jing Created. * */public class OverDrawState implements ICellState {? public boolean phone(CellContext ct) { System.out.println(ct.name + ": 處于透支狀態");? int minute = (int) (Math.random() * 10 + 1);// 隨機產生打電話分鐘數 ct.cost(minute); //some save code return false; }?} package pattern.chp08.state.cellState;?/** * 類描述:停機狀態 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:36:23 AM Jing Created. * */public class StopState implements ICellState {? public boolean phone(CellContext ct) { System.out.println(ct.name + ": 處于停機狀態"); return false; }?} ?package pattern.chp08.state.cellState;?/** * 類描述:手機上下文狀態類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:30:09 AM Jing Created. * */public class CellContext {? String strPhone;// 電話號碼 String name;// 姓名 float price;// 金額? public CellContext(String strPhone, String name, float price) { this.strPhone = strPhone; this.name = name; this.price = price; } /** * * 方法說明:手機存錢 * * Author: Jing * Create Date: Dec 26, 2014 11:31:41 AM * * @param price * @return void */ public void save(float price){ this.price += price; } /** * * 方法說明:手機話費 * * Author: Jing * Create Date: Dec 26, 2014 11:32:13 AM * * @param minute * @return void */ public void cost(int minute){ this.price -= ICellState.COST_MINUTE * minute; } /** * * 方法說明:獲取不同手機狀態 * * Author: Jing * Create Date: Dec 26, 2014 11:33:15 AM * * @return * @return boolean */ public boolean call(){ ICellState state = null; if(price > ICellState.NORMAL_LIMIT){ state = new NormalState(); }else if(price < ICellState.STOP_LIMIT){ state = new StopState(); }else{ state = new OverDrawState(); } state.phone(this); return true; } ?} /** * 類描述: * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 2:25:14 PM Jing Created. * */public class Test {? public static void main(String[] args) { CellContext c = new CellContext("213130", "LaoLiu", 1); c.call(); c.call(); }} 5,應用探索 計算機內存監控 ?package pattern.chp08.state.ctrl;?import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;?import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;?/** * 類描述:參數控制面板 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 2:35:38 PM Jing Created. * */public class CtrlPanel extends JPanel {? private static final long serialVersionUID = -6539318368246202726L;? JComponent[] c = { new JTextField(4), new JTextField(4), new JButton("開始檢測"), new JButton("停止檢測") };? boolean bmark[][] = { { true, true, true, false }, { false, false, false, true } };? ActionListener startAct = new ActionListener() {// 開始檢測 按鈕響應事件? public void actionPerformed(ActionEvent e) {? setState(1);// 設置組件為初始狀態? int high = Integer.parseInt(((JTextField) c[0]).getText()); int low = Integer.parseInt(((JTextField) c[1]).getText());? Container c = CtrlPanel.this.getParent(); String className = c.getClass().getName(); while (!"pattern.chp08.state.ctrl.MyFrame".equalsIgnoreCase(className)) {? c = c.getParent(); className = c.getClass().getName(); } ((MyFrame) c).startMonitor(high, low); }? };? ActionListener stopAct = new ActionListener() {// 停止檢測 按鈕響應? public void actionPerformed(ActionEvent e) {? setState(0); Container c = CtrlPanel.this.getParent(); String className = c.getClass().getName(); while (!"pattern.chp08.state.ctrl.MyFrame".equalsIgnoreCase(className)) {? c = c.getParent(); className = c.getClass().getName(); } ((MyFrame) c).stopMonitor(); } };? public CtrlPanel() {? add(new JLabel("優良")); add(c[0]); add(new JLabel("良好")); add(c[1]); add(c[2]); add(c[3]); setState(0);// 設置初始? ((JButton) c[2]).addActionListener(startAct); ((JButton) c[3]).addActionListener(stopAct);? }? /** * * 方法說明:設置按鈕狀態 * * Author: Jing Create Date: Dec 26, 2014 2:42:17 PM * * @param nState * @return void */ void setState(int nState) {? for (int i = 0; i < bmark[nState].length; i++) {? c[i].setEnabled(bmark[nState][i]); } }?} ?package pattern.chp08.state.ctrl;?import javax.swing.Box;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.border.BevelBorder;?/** * 類描述:中間數值展示面板類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:02:21 PM Jing Created. * */public class ContentPanel extends JPanel {? private static final long serialVersionUID = 3347768107958337339L; JTextField totalField = new JTextField(20);//總內存展示 JTextField freeField = new JTextField(20);//空閑內存顯示 JTextField ratioField = new JTextField(20);//空閑率展示 @SuppressWarnings("static-access") public ContentPanel() { totalField.setEditable(false); freeField.setEditable(false); ratioField.setEditable(false); Box b1 = Box.createVerticalBox(); b1.add(new JLabel("總內存:")); b1.add(b1.createVerticalStrut(16)); b1.add(new JLabel("空閑內存:")); b1.add(b1.createVerticalStrut(16)); b1.add(new JLabel("所占比例:")); b1.add(b1.createVerticalStrut(16)); Box b2 = 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(new BevelBorder(BevelBorder.RAISED)); } /** * * 方法說明:設置對應Field值 * * Author: Jing * Create Date: Dec 26, 2014 3:11:22 PM * * @param value * @param free * @param ratio * @return void */ void setValue(long value, long free, long ratio){ totalField.setText(value + " M"); freeField.setText(free + " M"); ratioField.setText(ratio + "%"); } } ?package pattern.chp08.state.ctrl;?import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;?/** * 類描述:上下文類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:24:15 PM Jing Created. * */public class StatePanel extends JPanel {? private static final long serialVersionUID = 1L;? JTextField txtInfo = new JTextField(4); JTextField txtHour = new JTextField(10); IState state; int mark = -1;? public StatePanel() {? add(new JLabel("當前內存狀態: ")); add(txtInfo); add(new JLabel("持續時間: ")); add(txtHour); txtInfo.setEnabled(false); txtHour.setEnabled(false); }? /* * 設置內存狀態 */ public void setState(int mark) {? if (this.mark == mark) {// 內存無變化? return; } this.mark = mark; switch (mark) { case 1: state = new HighState(); break; case 2: state = new MidState(); break; case 3: state = new LowState(); break; } }? /** * * 方法說明:設置對應值 * * Author: Jing Create Date: Dec 26, 2014 3:31:39 PM * * @return void */ public void process() {? txtInfo.setText(state.getStateInfo()); int size = state.getStateInterval(); //DecimalFormat df = new DecimalFormat("0.00"); txtHour.setText("" + /*df.format((float) size / 3600)*/ size + " S"); }?}
package pattern.chp08.state.ctrl;?/** * 類描述:狀態接口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:17:18 PM Jing Created. * */public interface IState { /** * * 方法說明:獲取狀態信息 * * Author: Jing Create Date: Dec 26, 2014 3:17:45 PM * * @return * @return String */ String getStateInfo();? /** * * 方法說明:獲取統計頻率 * * Author: Jing Create Date: Dec 26, 2014 3:18:12 PM * * @return * @return int */ int getStateInterval();} package pattern.chp08.state.ctrl;?/** * 類描述:內存緊張 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:19:28 PM Jing Created. * */public class LowState implements IState {? private int times;? public String getStateInfo() { //some other code //此處可設置通知管理員等其他代碼 return "一般"; }? public int getStateInterval() {? return times++; }?} package pattern.chp08.state.ctrl;?/** * 類描述:內存充足 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:18:56 PM Jing Created. * */public class HighState implements IState {? private int times;? public String getStateInfo() { //some other code //此處可設置通知管理員等其他代碼 return "充足"; }? public int getStateInterval() { return times++; }?} package pattern.chp08.state.ctrl;?/** * 類描述:內存良好 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:19:12 PM Jing Created. * */public class MidState implements IState {? private int times; public String getStateInfo() { //some other code //此處可設置通知管理員等其他代碼 return "良好"; }? public int getStateInterval() {? return times++; }?} ?package pattern.chp08.state.ctrl;?import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;?import javax.swing.JFrame;import javax.swing.Timer;?import sun.management.ManagementFactory;?import com.sun.management.OperatingSystemMXBean;?/** * 類描述:主窗口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:47:44 PM Jing Created. * */public class MyFrame extends JFrame implements ActionListener {? private static final long serialVersionUID = 1L;? CtrlPanel ctrlPanel = new CtrlPanel();// 參數面板 ContentPanel contentPanel = new ContentPanel();// 數值顯示面板 StatePanel statePanel = new StatePanel();// 狀態面板? Timer timer = new Timer(1000, this);// 定時器? int high, mid;? /** * * 方法說明:初始化 * * Author: Jing Create Date: Dec 26, 2014 3:51:54 PM * * @return void */ public void init() {? add(ctrlPanel, BorderLayout.NORTH); add(contentPanel, BorderLayout.CENTER); add(statePanel, BorderLayout.SOUTH); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500, 220); setVisible(true); }? /** * * 方法說明:啟動自動檢測 * * Author: Jing Create Date: Dec 26, 2014 3:53:53 PM * * @param high * @param mid * @return void */ public void startMonitor(int high, int mid) {? this.high = high; this.mid = mid;? timer.start();? }? /** * * 方法說明:停止檢測 * * Author: Jing Create Date: Dec 26, 2014 3:54:51 PM * * @return void */ public void stopMonitor() {? timer.stop(); }? public void actionPerformed(ActionEvent e) {// 定時器響應方法? OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory .getOperatingSystemMXBean(); long total = osmxb.getTotalPhysicalMemorySize(); long free = osmxb.getFreePhysicalMemorySize(); int ratio = (int) (free * 100L / total);? contentPanel.setValue(total / (1024 * 1024), free / (1024 * 1024), ratio);? int mark = -1; if (ratio >= high) {? mark = 1; } else if (ratio < mid) {? mark = 3; } else {? mark = 2; }? statePanel.setState(mark); statePanel.process(); }?} package pattern.chp08.state.ctrl;?/** * 類描述: * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 4:02:27 PM Jing Created. * */public class Test {? public static void main(String[] args) { new MyFrame().init(); }} 運行界面:
-1,上下文環境Context:定義客戶程序需要的接口并維護一個具體狀態角色的實例,將與狀態相關的操作委托給當前的Concrete ?State對象來處理。 -2,抽象狀態State:定義接口以封裝上下文環境的一個特定狀態的行為。 -3,具體狀態ConcreteState:具體狀態。 3,簡單代碼:
?package pattern.chp08.state.simple;?/** * 類描述:狀態抽象接口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:44:21 AM Jing Created. * */public interface IState { /** * * 方法說明:狀態更改 * * Author: Jing * Create Date: Dec 26, 2014 10:44:44 AM * * @return void */ void goState();} package pattern.chp08.state.simple;?/** * 類描述:狀態B * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:50:24 AM Jing Created. * */public class ConcreteStateB implements IState{? public void goState() { System.out.println("ConcreteStateB"); }?} package pattern.chp08.state.simple;?/** * 類描述:狀態A * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:50:04 AM Jing Created. * */public class ConcreteStateA implements IState {? public void goState() { System.out.println("ConcreteStateA"); }?} package pattern.chp08.state.simple;?/** * 類描述:上下文 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 10:52:03 AM Jing Created. * */public class Context {? private IState state;? public void setState(IState state) { this.state = state; } /** * * 方法說明:根據條件選擇某種狀態 * * Author: Jing * Create Date: Dec 26, 2014 10:52:51 AM * * @return void */ public void manage(){ state.goState(); }} 4,深入理解狀態模式 -1,利用上下文類控制狀態 ? ??? ? 手機應用,假設手機功能有存款和打電話,狀態有正常、透支、停機。使用狀態模式模擬:
? ??
?package pattern.chp08.state.cellState;?/** * 類描述:手機狀態接口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:04:09 AM Jing Created. * */public interface ICellState { /** * 正常狀態 */ public float NORMAL_LIMIT = 0; /** * 停機狀態 */ public float STOP_LIMIT = -1; /** * 話費標準 */ public float COST_MINUTE = 0.20F; /** * * 方法說明:電話 * * Author: Jing * Create Date: Dec 26, 2014 11:21:01 AM * * @param ct * @return * @return boolean */ boolean phone(CellContext ct); } package pattern.chp08.state.cellState;?/** * 類描述:正常狀態 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:35:54 AM Jing Created. * */public class NormalState implements ICellState {? public boolean phone(CellContext ct) {? System.out.println(ct.name + ": 處于正常狀態");? int minute = (int) (Math.random() * 10 + 1);// 隨機產生打電話分鐘數 ct.cost(minute); //some save code return false; }?} package pattern.chp08.state.cellState;?/** * 類描述:透支狀態下電話類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:36:47 AM Jing Created. * */public class OverDrawState implements ICellState {? public boolean phone(CellContext ct) { System.out.println(ct.name + ": 處于透支狀態");? int minute = (int) (Math.random() * 10 + 1);// 隨機產生打電話分鐘數 ct.cost(minute); //some save code return false; }?} package pattern.chp08.state.cellState;?/** * 類描述:停機狀態 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:36:23 AM Jing Created. * */public class StopState implements ICellState {? public boolean phone(CellContext ct) { System.out.println(ct.name + ": 處于停機狀態"); return false; }?} ?package pattern.chp08.state.cellState;?/** * 類描述:手機上下文狀態類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 11:30:09 AM Jing Created. * */public class CellContext {? String strPhone;// 電話號碼 String name;// 姓名 float price;// 金額? public CellContext(String strPhone, String name, float price) { this.strPhone = strPhone; this.name = name; this.price = price; } /** * * 方法說明:手機存錢 * * Author: Jing * Create Date: Dec 26, 2014 11:31:41 AM * * @param price * @return void */ public void save(float price){ this.price += price; } /** * * 方法說明:手機話費 * * Author: Jing * Create Date: Dec 26, 2014 11:32:13 AM * * @param minute * @return void */ public void cost(int minute){ this.price -= ICellState.COST_MINUTE * minute; } /** * * 方法說明:獲取不同手機狀態 * * Author: Jing * Create Date: Dec 26, 2014 11:33:15 AM * * @return * @return boolean */ public boolean call(){ ICellState state = null; if(price > ICellState.NORMAL_LIMIT){ state = new NormalState(); }else if(price < ICellState.STOP_LIMIT){ state = new StopState(); }else{ state = new OverDrawState(); } state.phone(this); return true; } ?} /** * 類描述: * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 2:25:14 PM Jing Created. * */public class Test {? public static void main(String[] args) { CellContext c = new CellContext("213130", "LaoLiu", 1); c.call(); c.call(); }} 5,應用探索 計算機內存監控 ?package pattern.chp08.state.ctrl;?import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;?import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;?/** * 類描述:參數控制面板 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 2:35:38 PM Jing Created. * */public class CtrlPanel extends JPanel {? private static final long serialVersionUID = -6539318368246202726L;? JComponent[] c = { new JTextField(4), new JTextField(4), new JButton("開始檢測"), new JButton("停止檢測") };? boolean bmark[][] = { { true, true, true, false }, { false, false, false, true } };? ActionListener startAct = new ActionListener() {// 開始檢測 按鈕響應事件? public void actionPerformed(ActionEvent e) {? setState(1);// 設置組件為初始狀態? int high = Integer.parseInt(((JTextField) c[0]).getText()); int low = Integer.parseInt(((JTextField) c[1]).getText());? Container c = CtrlPanel.this.getParent(); String className = c.getClass().getName(); while (!"pattern.chp08.state.ctrl.MyFrame".equalsIgnoreCase(className)) {? c = c.getParent(); className = c.getClass().getName(); } ((MyFrame) c).startMonitor(high, low); }? };? ActionListener stopAct = new ActionListener() {// 停止檢測 按鈕響應? public void actionPerformed(ActionEvent e) {? setState(0); Container c = CtrlPanel.this.getParent(); String className = c.getClass().getName(); while (!"pattern.chp08.state.ctrl.MyFrame".equalsIgnoreCase(className)) {? c = c.getParent(); className = c.getClass().getName(); } ((MyFrame) c).stopMonitor(); } };? public CtrlPanel() {? add(new JLabel("優良")); add(c[0]); add(new JLabel("良好")); add(c[1]); add(c[2]); add(c[3]); setState(0);// 設置初始? ((JButton) c[2]).addActionListener(startAct); ((JButton) c[3]).addActionListener(stopAct);? }? /** * * 方法說明:設置按鈕狀態 * * Author: Jing Create Date: Dec 26, 2014 2:42:17 PM * * @param nState * @return void */ void setState(int nState) {? for (int i = 0; i < bmark[nState].length; i++) {? c[i].setEnabled(bmark[nState][i]); } }?} ?package pattern.chp08.state.ctrl;?import javax.swing.Box;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.border.BevelBorder;?/** * 類描述:中間數值展示面板類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:02:21 PM Jing Created. * */public class ContentPanel extends JPanel {? private static final long serialVersionUID = 3347768107958337339L; JTextField totalField = new JTextField(20);//總內存展示 JTextField freeField = new JTextField(20);//空閑內存顯示 JTextField ratioField = new JTextField(20);//空閑率展示 @SuppressWarnings("static-access") public ContentPanel() { totalField.setEditable(false); freeField.setEditable(false); ratioField.setEditable(false); Box b1 = Box.createVerticalBox(); b1.add(new JLabel("總內存:")); b1.add(b1.createVerticalStrut(16)); b1.add(new JLabel("空閑內存:")); b1.add(b1.createVerticalStrut(16)); b1.add(new JLabel("所占比例:")); b1.add(b1.createVerticalStrut(16)); Box b2 = 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(new BevelBorder(BevelBorder.RAISED)); } /** * * 方法說明:設置對應Field值 * * Author: Jing * Create Date: Dec 26, 2014 3:11:22 PM * * @param value * @param free * @param ratio * @return void */ void setValue(long value, long free, long ratio){ totalField.setText(value + " M"); freeField.setText(free + " M"); ratioField.setText(ratio + "%"); } } ?package pattern.chp08.state.ctrl;?import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;?/** * 類描述:上下文類 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:24:15 PM Jing Created. * */public class StatePanel extends JPanel {? private static final long serialVersionUID = 1L;? JTextField txtInfo = new JTextField(4); JTextField txtHour = new JTextField(10); IState state; int mark = -1;? public StatePanel() {? add(new JLabel("當前內存狀態: ")); add(txtInfo); add(new JLabel("持續時間: ")); add(txtHour); txtInfo.setEnabled(false); txtHour.setEnabled(false); }? /* * 設置內存狀態 */ public void setState(int mark) {? if (this.mark == mark) {// 內存無變化? return; } this.mark = mark; switch (mark) { case 1: state = new HighState(); break; case 2: state = new MidState(); break; case 3: state = new LowState(); break; } }? /** * * 方法說明:設置對應值 * * Author: Jing Create Date: Dec 26, 2014 3:31:39 PM * * @return void */ public void process() {? txtInfo.setText(state.getStateInfo()); int size = state.getStateInterval(); //DecimalFormat df = new DecimalFormat("0.00"); txtHour.setText("" + /*df.format((float) size / 3600)*/ size + " S"); }?}
package pattern.chp08.state.ctrl;?/** * 類描述:狀態接口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:17:18 PM Jing Created. * */public interface IState { /** * * 方法說明:獲取狀態信息 * * Author: Jing Create Date: Dec 26, 2014 3:17:45 PM * * @return * @return String */ String getStateInfo();? /** * * 方法說明:獲取統計頻率 * * Author: Jing Create Date: Dec 26, 2014 3:18:12 PM * * @return * @return int */ int getStateInterval();} package pattern.chp08.state.ctrl;?/** * 類描述:內存緊張 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:19:28 PM Jing Created. * */public class LowState implements IState {? private int times;? public String getStateInfo() { //some other code //此處可設置通知管理員等其他代碼 return "一般"; }? public int getStateInterval() {? return times++; }?} package pattern.chp08.state.ctrl;?/** * 類描述:內存充足 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:18:56 PM Jing Created. * */public class HighState implements IState {? private int times;? public String getStateInfo() { //some other code //此處可設置通知管理員等其他代碼 return "充足"; }? public int getStateInterval() { return times++; }?} package pattern.chp08.state.ctrl;?/** * 類描述:內存良好 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:19:12 PM Jing Created. * */public class MidState implements IState {? private int times; public String getStateInfo() { //some other code //此處可設置通知管理員等其他代碼 return "良好"; }? public int getStateInterval() {? return times++; }?} ?package pattern.chp08.state.ctrl;?import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;?import javax.swing.JFrame;import javax.swing.Timer;?import sun.management.ManagementFactory;?import com.sun.management.OperatingSystemMXBean;?/** * 類描述:主窗口 * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 3:47:44 PM Jing Created. * */public class MyFrame extends JFrame implements ActionListener {? private static final long serialVersionUID = 1L;? CtrlPanel ctrlPanel = new CtrlPanel();// 參數面板 ContentPanel contentPanel = new ContentPanel();// 數值顯示面板 StatePanel statePanel = new StatePanel();// 狀態面板? Timer timer = new Timer(1000, this);// 定時器? int high, mid;? /** * * 方法說明:初始化 * * Author: Jing Create Date: Dec 26, 2014 3:51:54 PM * * @return void */ public void init() {? add(ctrlPanel, BorderLayout.NORTH); add(contentPanel, BorderLayout.CENTER); add(statePanel, BorderLayout.SOUTH); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500, 220); setVisible(true); }? /** * * 方法說明:啟動自動檢測 * * Author: Jing Create Date: Dec 26, 2014 3:53:53 PM * * @param high * @param mid * @return void */ public void startMonitor(int high, int mid) {? this.high = high; this.mid = mid;? timer.start();? }? /** * * 方法說明:停止檢測 * * Author: Jing Create Date: Dec 26, 2014 3:54:51 PM * * @return void */ public void stopMonitor() {? timer.stop(); }? public void actionPerformed(ActionEvent e) {// 定時器響應方法? OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory .getOperatingSystemMXBean(); long total = osmxb.getTotalPhysicalMemorySize(); long free = osmxb.getFreePhysicalMemorySize(); int ratio = (int) (free * 100L / total);? contentPanel.setValue(total / (1024 * 1024), free / (1024 * 1024), ratio);? int mark = -1; if (ratio >= high) {? mark = 1; } else if (ratio < mid) {? mark = 3; } else {? mark = 2; }? statePanel.setState(mark); statePanel.process(); }?} package pattern.chp08.state.ctrl;?/** * 類描述: * * @author: Jing * @version $Id: Exp$ * * History: Dec 26, 2014 4:02:27 PM Jing Created. * */public class Test {? public static void main(String[] args) { new MyFrame().init(); }} 運行界面:
轉載于:https://www.cnblogs.com/jingLongJun/p/4491068.html
總結
以上是生活随笔為你收集整理的读书笔记_java设计模式深入研究 第八章 状态模式 State的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php多进程实现 亲测
- 下一篇: 通过Sqoop实现Mysql / Ora