iT邦幫忙

2023 iThome 鐵人賽

DAY 17
0
自我挑戰組

設計模式系列 第 17

Day17 - 狀態模式(State pattern)

  • 分享至 

  • xImage
  •  

介紹
狀態模式讓物件的行為隨著內部狀態不同而改變。

C++範例

#include <iostream>
#include <string>

class PlayerState
{
public:
    PlayerState(const std::string& stateName) : m_stateName(stateName)
    {
    }
    
    virtual ~PlayerState() {}
    
    virtual void Attack() = 0;
    virtual void Duck() = 0;
    
    std::string GetStateName() const
    {
        return m_stateName;
    }
    
    private:
        const std::string m_stateName;
};

class JumpState : public PlayerState
{
public:
    JumpState() : PlayerState("Jumping")
    {
    }
    
    ~JumpState() {}

    void Attack() override
    {
        std::cout << "Use jump kick" << std::endl;
    }
    void Duck() override
    {
        std::cout << "(Player is jumping, can't duck)" << std::endl;
    }
};

class DuckState : public PlayerState
{
public:
    DuckState() : PlayerState("Ducking")
    {
    }
    
    ~DuckState() {}

    void Attack() override
    {
        std::cout << "Use duck kick" << std::endl;
    }
    void Duck() override
    {
        std::cout << "(Player is ducking, can't duck again)" << std::endl;
    }
};

class Player
{
public:
    Player(){};
    virtual ~Player() {}

    void SetState(PlayerState *state)
    {
        m_state = state;
        std::cout << "-- The player is in " + m_state->GetStateName() + " state" << std::endl;
    }
    void Attack()
    {
        m_state->Attack();
    }
    void Duck()
    {
        m_state->Duck();
    }

private:
    PlayerState *m_state;
};

int main()
{
    JumpState jumpState;
    DuckState duckState;

    Player player;

    // 設定玩家正在跳躍狀態
    player.SetState(&jumpState);
    player.Attack();
    player.Duck();

    // 設定玩家正在蹲下狀態
    player.SetState(&duckState);
    player.Attack();
    player.Duck();

    return 0;
}

Output:

-- The player is in Jumping state
Use jump kick
(Player is jumping, can't duck)
-- The player is in Ducking state
Use duck kick
(Player is ducking, can't duck again)

上一篇
Day16 - 策略模式(Strategy pattern)
下一篇
Day18 - 命令模式(Command pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言