c++:設計模式訓練

寫一個鳥類:有一個多態函數:run
寫一個企鵝類,繼承自鳥類:重寫 run?
寫一個鴕鳥類,繼承自鳥類,重寫 run
寫一個老鷹類,繼承自鳥類,重寫run
寫一個鳥籠,能夠存放 不同的鳥類對象
鳥籠是什么類型的自己想
鳥籠初始化的時候,4個不同的鳥類,至少有一個對象在鳥籠里面
寫一個函數,叫做 open_cage
實現效果:放跑里面的所有鳥類,讓所有鳥 run
使用觀察者模式實現

from abc import ABC, abstractmethod
from typing import List# 鳥類接口
class Bird(ABC):@abstractmethoddef run(self) -> str:pass# 具體鳥類實現
class Penguin(Bird):def run(self) -> str:return "企鵝搖擺著逃走了"class Ostrich(Bird):def run(self) -> str:return "鴕鳥大步流星地跑開了"class Eagle(Bird):def run(self) -> str:return "老鷹展翅高飛,離開了鳥籠"# 觀察者接口
class Observer(ABC):@abstractmethoddef update(self) -> None:pass# 鳥籠類 - 被觀察對象
class BirdCage:def __init__(self):self._birds: List[Bird] = [Penguin(),Ostrich(),Eagle(),Penguin()  # 至少有一個重復的鳥類]self._observers: List[Observer] = []def add_observer(self, observer: Observer) -> None:self._observers.append(observer)def remove_observer(self, observer: Observer) -> None:self._observers.remove(observer)def notify_observers(self) -> None:for observer in self._observers:observer.update()def open(self) -> List[str]:"""打開鳥籠,放跑所有鳥類"""results = [bird.run() for bird in self._birds]self._birds.clear()self.notify_observers()  # 通知觀察者鳥籠已空return results# 實現一個簡單的觀察者
class CageWatcher(Observer):def __init__(self, cage: BirdCage):self._cage = cageself._cage.add_observer(self)def update(self) -> None:print("觀察者: 鳥籠現在空了!")# 釋放鳥類的函數
def open_cage(cage: BirdCage) -> None:"""放跑鳥籠中的所有鳥類"""results = cage.open()for result in results:print(result)# 使用示例
if __name__ == "__main__":cage = BirdCage()watcher = CageWatcher(cage)print("打開鳥籠...")open_cage(cage)

使用 策略模式 + 簡單工廠模式實現以下功能
有一個英雄類,擁有私有成員: hp ,atk,dep
英雄可以打怪掉落武器:怪物可以掉落3種武器:
長劍,匕首,斧頭
英雄裝備長劍,獲得2點hp
英雄裝備匕首,獲得2點atk
英雄裝備斧頭,獲得2點def
英雄裝備不同的武器,使用策略模式去實現
注意:測試的時候,英雄在更換武器的時候,記得使用策略模式,將英雄之間裝備的武器屬性扣除后,再增加新屬性
打敗怪物掉落什么武器,自己設計,但是要求怪物掉落武器是一個簡單工廠模式

方案一:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;class Weapon;// 英雄類定義
class Hero {
private:int hp = 0;int atk = 0;int def = 0;Weapon* w = NULL;public:void setHp(int h) { hp = h; }void setAtk(int a) { atk = a; }void setDef(int a) { def = a; }int getHp() { return hp; }int getAtk() { return atk; }int getDef() { return def; }void choice_weapon(Weapon* w);void equip_weapon();void show() {cout << "hp = " << hp << endl<< "atk = " << atk << endl<< "def = " << def << endl<< "===========" << endl;}
};// 武器基類定義
class Weapon {
public:virtual void equip(Hero& hero) = 0;virtual void drop(Hero& hero) = 0;virtual ~Weapon() {}
};// 長劍類,繼承自武器基類
class Sword : public Weapon {
public:void equip(Hero& hero) override {cout << "英雄裝備了長劍" << endl;int hero_new_hp = hero.getHp() + 2;hero.setHp(hero_new_hp);}void drop(Hero& hero) override {int hero_new_hp = hero.getHp() - 2;hero.setHp(hero_new_hp);}
};// 短劍類,繼承自武器基類
class Blade : public Weapon {
public:void equip(Hero& hero) override {cout << "英雄裝備了短劍" << endl;int hero_new_atk = hero.getAtk() + 2;hero.setAtk(hero_new_atk);}void drop(Hero& hero) override {int hero_new_atk = hero.getAtk() - 2;hero.setAtk(hero_new_atk);}
};// 斧頭類,繼承自武器基類
class Axe : public Weapon {
public:void equip(Hero& hero) override {cout << "英雄裝備了斧頭" << endl;int hero_new_def = hero.getDef() + 2;hero.setDef(hero_new_def);}void drop(Hero& hero) override {int hero_new_def = hero.getDef() - 2;hero.setDef(hero_new_def);}
};// 怪物類,作為武器工廠,生成不同武器
class Monster {
public:Weapon* createWeapon() {int val = rand() % 3;// cout << "val = " << val << endl;if (val == 0) {return new Sword;} else if (val == 1) {return new Blade;} else if (val == 2) {return new Axe;}return nullptr;}
};// 英雄類中 choice_weapon 方法實現
void Hero::choice_weapon(Weapon* w) {if (this->w != NULL) {// 選擇新武器,記得脫掉上一件武器this->w->drop(*this);  // 脫掉上一件武器delete this->w;  // 銷毀上一件武器}this->w = w;  // 記錄新的武器
}// 英雄類中 equip_weapon 方法實現
void Hero::equip_weapon() {this->w->equip(*this);
}// 主函數,程序入口
int main(int argc, const char** argv) {srand((unsigned int)time(0));  // 更改隨機種子,以時間為依據種下隨機種子Hero hero;Monster mon;while (1) {Weapon* w = mon.createWeapon();hero.choice_weapon(w);hero.equip_weapon();hero.show();// step(1);  // 該函數未定義,若需使用需補充實現,這里先注釋}return 0;
}

方案二:

from abc import ABC, abstractmethod
from enum import Enum
import random# 武器策略接口
class WeaponStrategy(ABC):@abstractmethoddef equip(self, hero) -> None:pass@abstractmethoddef unequip(self, hero) -> None:pass# 具體武器策略
class LongswordStrategy(WeaponStrategy):def equip(self, hero) -> None:hero._hp += 2hero._current_weapon = selfdef unequip(self, hero) -> None:hero._hp -= 2hero._current_weapon = Noneclass DaggerStrategy(WeaponStrategy):def equip(self, hero) -> None:hero._atk += 2hero._current_weapon = selfdef unequip(self, hero) -> None:hero._atk -= 2hero._current_weapon = Noneclass AxeStrategy(WeaponStrategy):def equip(self, hero) -> None:hero._def += 2hero._current_weapon = selfdef unequip(self, hero) -> None:hero._def -= 2hero._current_weapon = None# 武器類型枚舉
class WeaponType(Enum):LONGSWORD = "longsword"DAGGER = "dagger"AXE = "axe"# 武器工廠
class WeaponFactory:@staticmethoddef create_weapon(weapon_type: WeaponType) -> WeaponStrategy:if weapon_type == WeaponType.LONGSWORD:return LongswordStrategy()elif weapon_type == WeaponType.DAGGER:return DaggerStrategy()elif weapon_type == WeaponType.AXE:return AxeStrategy()else:raise ValueError(f"未知武器類型: {weapon_type}")@staticmethoddef from_monster_drop() -> WeaponStrategy:"""模擬怪物掉落武器"""weapon_type = random.choice(list(WeaponType))return WeaponFactory.create_weapon(weapon_type)# 英雄類
class Hero:def __init__(self, hp: int, atk: int, defense: int):self._hp = hpself._atk = atkself._def = defenseself._current_weapon: WeaponStrategy | None = Nonedef get_status(self) -> str:weapon_name = self._get_weapon_name()return f"HP: {self._hp}, ATK: {self._atk}, DEF: {self._def}, 武器: {weapon_name}"def _get_weapon_name(self) -> str:if self._current_weapon is None:return "無"elif isinstance(self._current_weapon, LongswordStrategy):return "長劍"elif isinstance(self._current_weapon, DaggerStrategy):return "匕首"elif isinstance(self._current_weapon, AxeStrategy):return "斧頭"return "未知武器"def equip_weapon(self, weapon: WeaponStrategy) -> None:"""裝備新武器,自動卸下當前武器"""if self._current_weapon:self._current_weapon.unequip(self)weapon.equip(self)print(f"裝備了{self._get_weapon_name()}")def defeat_monster(self) -> WeaponStrategy:"""擊敗怪物,獲得掉落武器"""weapon = WeaponFactory.from_monster_drop()print(f"擊敗怪物,掉落了{self._get_weapon_name_from_type(weapon)}")return weapondef _get_weapon_name_from_type(self, weapon: WeaponStrategy) -> str:if isinstance(weapon, LongswordStrategy):return "長劍"elif isinstance(weapon, DaggerStrategy):return "匕首"elif isinstance(weapon, AxeStrategy):return "斧頭"return "未知武器"# 測試代碼
if __name__ == "__main__":# 創建英雄hero = Hero(hp=10, atk=5, defense=3)print("初始狀態:", hero.get_status())# 擊敗怪物獲得武器并裝備weapon1 = hero.defeat_monster()hero.equip_weapon(weapon1)print("當前狀態:", hero.get_status())# 再次擊敗怪物獲得新武器并裝備weapon2 = hero.defeat_monster()hero.equip_weapon(weapon2)print("當前狀態:", hero.get_status())# 手動更換武器weapon3 = WeaponFactory.create_weapon(WeaponType.AXE)hero.equip_weapon(weapon3)print("當前狀態:", hero.get_status())    

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/91990.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/91990.shtml
英文地址,請注明出處:http://en.pswp.cn/web/91990.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

配置Mybatis環境

配置Mybatis環境MyBatis是什么配置Mybatis環境MyBatis是什么 MyBatis 一個支持普通 SQL 查詢、存儲過程以及高級映射的持久層框架。MyBatis 免除了幾乎所有的 JDBC 代碼以及設置參數和獲取結果集的工作&#xff0c;使得開發者可以更專注于 SQL 本身&#xff0c;而不必花費過多…

生產環境中基于Istio的Kubernetes多集群灰度發布架構實戰經驗分享

生產環境中基于Istio的Kubernetes多集群灰度發布架構實戰經驗分享 在大規模分布式微服務架構中&#xff0c;如何在多集群環境下平滑、安全地發布新版本&#xff0c;一直是保證高可用、高可靠的關鍵需求。本文以真實生產環境案例為基礎&#xff0c;分享我們團隊基于Istio Servic…

Kubernetes(k8s)之認識Pod

01了解Pod Pod是Kubernetes創建或部署的最小/最簡單的基本單位,一個Pod代表集群上正在運行的一個進程。 一個Pod封裝一個應用容器(也可以有多個容器),存儲資源、一個獨立的網絡IP以及管理控制容器運行方式的策略選項。它可能由單個容器或多個容器共享組成的資源。 Kubern…

Nginx服務做負載均衡網關

1. 概述 內部Nginx服務器做服務網關&#xff0c;代理后端應用服務&#xff0c;卸載ssl域名證書&#xff0c;將接收的https請求&#xff0c;轉發至后端http服務。華為防火墻負責NAT&#xff0c;啟用服務器負載均衡功能&#xff0c;將公網虛擬IP端口映射到內部多臺Nginx服務器上…

十三、請求響應-請求:日期參數和JSON參數

日期參數代碼&#xff1a;日期參數 //日期時間參數RequestMapping("/dataParam")public String dataParam(DateTimeFormat(pattern "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime){System.out.println(updateTime);return "OK";}結果JSON參…

可信數據庫大會現場,TDengine 時序數據庫展示核電場景下的高性能與 AI 創新

設備在升級&#xff0c;場站在擴建&#xff0c;但數據系統卻還在“跟不上”。這正是許多核電企業在推進數字化轉型過程中最真實的感受。高頻采集、長周期存儲、精度要求高……這些構成了對數據庫系統的“煉獄級考驗”。在這樣一個背景下&#xff0c;國產數據庫的能力邊界正在被…

ctflearn-POST practice

靶場地址&#xff1a;165.227.106.113/post.php 解題&#xff1a; 一.分析題目 提示&#xff1a; 知道要用POST請求提交表單&#xff0c;看一下源碼信息 得到可能需要用post請求方式去提交表單&#xff0c;并且傳數據admin和password&#xff0c;這邊提供兩種方式 方法一&…

FPGA實現OV7670攝像頭圖像處理至VGA顯示器

本文還有配套的精品資源&#xff0c;點擊獲取 簡介&#xff1a;本項目基于FPGA技術&#xff0c;結合OV7670攝像頭傳感器進行視頻捕獲&#xff0c;經SDRAM存儲&#xff0c;并通過VGA顯示器展示。同時&#xff0c;集成了中值濾波算法提高圖像清晰度。該項目涉及數字圖像處理系…

使用python寫一套完整的智能體小程序

創建一個簡單的智能體&#xff08;Agent&#xff09;程序在人工智能和自動化任務中&#xff0c;智能體&#xff08;Agent&#xff09;是指能夠感知環境并通過決策和行動來實現目標的實體。Python 提供了豐富的庫和框架&#xff0c;可以用于構建智能體程序&#xff0c;例如使用 …

電商項目_性能優化_海量數據讀寫、存儲、檢索

海量數據讀寫方式選擇高并發讀寫場景分析無論任何業務系統&#xff0c;無非就是兩個操作&#xff1a;寫和讀。 在海量數據和高并發的場景下&#xff0c;寫和讀就會成為系統性能的瓶頸。下面分析不同業務場景下面臨的問題&#xff1a;側重“高并發讀”的系統場景1&#xff1a;搜…

RabbitMQ面試精講 Day 9:優先級隊列與惰性隊列

【RabbitMQ面試精講 Day 9】優先級隊列與惰性隊列 文章標簽 RabbitMQ,優先級隊列,惰性隊列,消息隊列,面試技巧,系統架構 文章簡述 本文是"RabbitMQ面試精講"系列第9天&#xff0c;深入解析優先級隊列與惰性隊列的實現原理與實戰應用。文章詳細講解優先級隊列的排…

[硬件電路-121]:模擬電路 - 信號處理電路 - 模擬電路中常見的難題

模擬電路設計是電子工程中極具挑戰性的領域&#xff0c;其核心難題源于信號的連續性、元件的非理想特性以及環境干擾的復雜性。以下是模擬電路中常見的難題及其技術本質與解決方案&#xff1a;1. 噪聲與干擾&#xff1a;信號的“隱形殺手”技術本質&#xff1a;模擬信號對微小電…

Java 大視界 -- Java 大數據在智能交通智能停車誘導與車位共享優化中的應用(381)

Java 大視界 -- Java 大數據在智能交通智能停車誘導與車位共享優化中的應用&#xff08;381&#xff09;引言&#xff1a;正文&#xff1a;一、智能停車的 “老大難”&#xff1a;不只是 “車位少” 那么簡單1.1 車主與車位的 “錯位困境”1.1.1 信息滯后的 “睜眼瞎”1.1.2 車…

基于落霞歸雁思維框架的自動化測試實踐與探索

基于落霞歸雁思維框架的自動化測試實踐與探索 在當今快速發展的軟件開發領域&#xff0c;自動化測試已成為提高軟件質量和開發效率的關鍵環節。本文將結合落霞歸雁的思維框架——“觀察現象 → 找規律 → 應用規律 → 實踐驗證”&#xff0c;探討如何將其應用于自動化測試領域&…

Unity Shader編程進階:掌握高階渲染技術 C# 實戰案例

Unity Shader編程完全入門指南&#xff1a;從零到實戰 C# 本文將深入探討Unity Shader編程的高級技術&#xff0c;包括自定義光照模型、后處理效果、GPU實例化、表面著色器深度應用等&#xff0c;幫助開發者提升渲染效果與性能優化能力。 提示&#xff1a;內容純個人編寫&#…

(論文速讀)Text-IF:基于語義文本引導的退化感知交互式圖像融合方法

論文信息論文題目&#xff1a;Text-IF: Leveraging Semantic Text Guidance for Degradation-Aware and Interactive Image Fusion&#xff08;Text-IF:利用語義文本指導退化感知和交互式圖像融合&#xff09;會議&#xff1a;CVPR2024摘要&#xff1a;圖像融合的目的是將不同源…

python創建一個excel文件

以下是使用Python根據指定名稱創建Excel文件的兩種實現方法&#xff0c;根據需求選擇適合的方案&#xff1a;方法一&#xff1a;使用pandas庫&#xff08;適合結構化數據&#xff09; # 安裝依賴&#xff08;命令行執行&#xff09; # pip install pandas openpyxlimport panda…

C++高頻知識點(十四)

文章目錄66. 程序什么時候應該使用多線程&#xff0c;什么時候單線程效率高&#xff1f;67. 死鎖的原因和避免死鎖的避免預防死鎖&#xff1a;破壞持有并等待條件68. TCP擁塞控制四個階段輪換過程描述69. C的內存管理70. 構造函數可以是虛函數嗎&#xff0c;析構函數呢66. 程序…

淺窺Claude-Prompting for Agents的Talk

Prompting for Agents先說一句&#xff1a;顏值這么高&#xff0c;你倆要出道啊。此圖基本就是claude倡導的agent prompt結構了&#xff0c;可以看到經過一年時間的演變&#xff0c;基本都是follow這個結構去寫prompt。我比較喜歡用Role→react→task→histroy→few shot→rule…

【MySQL04】:基礎查詢

MySQL的基本查詢表的增刪查改 insert(插入) insert [info] table_name [(colume, [,colume] ...)] values (value_list) ...對于value_list我們通過,作為分隔符 插入替換我們使用on duplicate key update, 表示如果存在主鍵沖突, 會進行更新, 這個字段后面還有寫更新的字段repl…