zoukankan      html  css  js  c++  java
  • 状态模式

    一、简介

    1、状态模式中当一个对象的内部状态改变时允许改变其行为,这个对象看起来像是改变了其类。

    2、状态模式可以消化较大的分支,将每个分支放入一种状态中,减少了分支之间的耦合程度,又符合开闭原则。当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式。

    3、UML

    4、所属类别:行为型

    二、C++程序

     1 // 状态模式.cpp : 定义控制台应用程序的入口点。
     2 //
     3 
     4 #include "stdafx.h"
     5 #include<iostream>
     6 using namespace std;
     7 
     8 
     9 class State
    10 {
    11 public:
    12     State(){}
    13     virtual ~State(){}
    14     virtual void doit()=0;
    15 };
    16 
    17 
    18 class Havebreakfast:public State
    19 {
    20 private:
    21     State *current_state;
    22 public:
    23     Havebreakfast(){}
    24     virtual ~Havebreakfast(){}
    25     virtual void doit()
    26     {
    27         cout<<"吃早饭"<<endl;
    28         //current_state=new Havebreakfast();
    29         //current_state->doit();
    30     }
    31 };
    32 class Wash:public State
    33 {
    34 private:
    35     State *current_state;
    36 public:
    37     Wash(){}
    38     virtual ~Wash(){}
    39     virtual void doit()
    40     {
    41         cout<<"洗漱"<<endl;
    42         current_state=new Havebreakfast();
    43         current_state->doit();
    44     }
    45 };
    46 class Getup:public State
    47 {
    48 private:
    49     State *current_state;
    50 public:
    51     Getup(){}
    52     virtual ~Getup(){}
    53     virtual void doit()
    54     {
    55         cout<<"起床"<<endl;
    56         current_state=new Wash();
    57         current_state->doit();
    58     }
    59 };
    60 class Morning
    61 {
    62 private:
    63     State * current_state;
    64 public:
    65     Morning()
    66     {
    67         current_state=new Getup();
    68     }
    69     ~Morning(){};
    70     void doit()
    
    71     {
    72         current_state->doit();
    73     }
    74 };
    75 
    76 int _tmain(int argc, _TCHAR* argv[])
    77 {
    78     Morning *m=new Morning();
    79     m->doit();
    80     return 0;
    81 }
  • 相关阅读:
    JQuery[07]Dom操作
    系统钩子[02] 安装全局鼠标钩子
    [Java动态代理] 设计模式之代理模式
    对话框编程之模态对话框 [03]
    对话框编程之属性对话框 [05]
    [Java反射机制] 通过反射机制创建类的实例并调用其方法
    JQuery[06] 过滤器、相对选择器
    JQuery[04] 节点遍历
    JQuery[13] Ajax的简单应用
    JQuery[09] CSS样式操作/节点操作
  • 原文地址:https://www.cnblogs.com/bewolf/p/4235428.html
Copyright © 2011-2022 走看看