面向对象程序设计第七次实验课——状态模式

本文通过一个状态模式的例子,详细介绍了如何在面向对象编程中使用状态模式。状态模式允许对象在内部状态改变时改变其行为,使得对象看起来好像改变了它的类。文章探讨了多态的重要性,对比了使用状态模式与面向过程、基于对象解决方案的优缺点,并讨论了双向关联类的实现技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目要求是自己开脑洞想一个状态模式的例子,实现之。
例子详见后文。
状态模式简介:
http://www.cnblogs.com/wangjq/archive/2012/07/16/2593485.html

State.h

#pragma once
#include "Person.h"

class Person;
class State
{
    public:
        State() = default;
        ~State() = default;
        virtual void study(Person *per) = 0;
        virtual void play(Person *per) = 0;
        virtual void eat(Person *per) = 0;
        virtual void exam(Person *per) = 0;
        void sleep(Person *per);
};

State.cpp

#include "State.h"
#include "Person.h"
#include <iostream>
using namespace std;

void State::sleep(Person *per)
{
    cout << "Sound Sleep ~" << endl;
    cout << "a new day is coming ~" << endl;
    per -> setstate(per -> getNewState());
    return ;
}

Exciting.h

#pragma once
#include "State.h"

class Exciting : public State
{
    public:
        Exciting() = default;
        ~Exciting() = default;
        virtual void study(Person *per) override;
        virtual void play(Person *per) override;
        virtual void eat(Person *per) override;
        virtual void exam(Person *per) override;
};

Exciting.cpp

#include <iostream>
#include "Exciting.h"
#include "Person.h"
#include "Happy.h"
#include "Sad.h"
#include "Soso.h"
using namespace std;

void Exciting::study(Person *per)
{
    cout << "Excited! Study!" << endl;
    cout << "Gain lots of knowledge! You're content with yourself~" << endl;
    per -> setstate(new Happy);
    cout << "Get into Happy Mode ~" << endl;
    return ;
}

void Exciting::play(Person *per)
{
    cout << "Excited! Play!" << endl;
    cout << "You win a lot!" << endl;
    cout << "Still Exciting!" << endl;
}

void Exciting::eat(Person *per)
{
    cout << "Excited! Eat!" << endl;
    cout << "You eat too much!" << endl;
    per -> setstate(new Soso);
    cout << "Get into Soso Mode" << endl;
}

void
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值