写一个鸟类:有一个多态函数: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…