之前已经讨论过“一般与特殊”(继承与多态),但这里可以更深入地探讨,并补充一些新的视角和实例。
一、 一般与特殊方法论
- 一般化(Generalization)
核心思想:从多个特殊类中提取共同特征,形成一般化的父类或接口。
目的:实现代码复用,定义通用契约,建立层次结构。
实现方式:
继承:子类继承父类的属性和方法
接口:实现通用的接口契约
模板:使用泛型或模板定义通用算法
- 特殊化(Specialization)
核心思想:从一般化的父类或接口派生出具有特殊行为的子类。
目的:扩展或修改一般行为,实现多态,适应特定需求。
实现方式:
重写:覆盖父类方法以改变行为
扩展:添加新的属性和方法
特化:为通用算法提供特定类型的实现
- 两者关系
一般与特殊是面向对象编程的基石:
一般化定义共性,建立规范
特殊化实现特性,提供具体行为
多态允许以一般形式处理特殊对象
二、 实例说明:支付系统设计
将通过设计一个支付系统来展示一般与特殊的方法。
第一阶段:一般化设计 - 定义通用支付接口
python
Python - 一般化设计:定义通用支付接口
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
一般1:支付方式抽象
class PaymentMethod(ABC):
“”“支付方式的一般化抽象”“”
@abstractmethod
def authorize(self, amount: float, currency: str) -> Dict[str, Any]:
"""授权支付"""
pass
@abstractmethod
def capture(self, amount: float, transaction_id: str) -> Dict[str, Any]:
"""捕获支付(实际扣款)"""
pass
@abstractmethod
def refund(self, amount: float, transaction_id: str) -> Dict[str, Any]:
"""退款"""
pass
@abstractmethod
def void(self, transaction_id: str) -> Dict[str, Any]:
"""取消支付"""
pass
# 通用方法(可以有默认实现)
def validate_amount(self, amount: float) -> bool:
"""验证金额(通用逻辑)"""
return amount > 0 and amount <= 1000000 # 假设最大100万
def get_method_name(self) -> str:
"""获取支付方式名称"""
return self.__class__.__name__
一般2:支付处理器抽象
class PaymentProcessor(ABC):
“”“支付处理器的一般化抽象”“”
@abstractmethod
def process_payment(self,
payment_method: PaymentMethod,
amount: float,
currency: str,
**kwargs) -> Dict[str, Any]:
"""处理支付(模板方法)"""
pass
@abstractmethod
def get_supported_methods(self) -> list:
"""获取支持的支付方式"""
pass
# 模板方法:定义支付处理流程
def standard_payment_flow(self,
payment_method: PaymentMethod,
amount: float,
currency: str) -> Dict[str, Any]:
"""标准支付流程(模板方法)"""
# 1. 验证
if not payment_method.validate_amount(amount):
return {"success": False, "error": "Invalid amount"}
# 2. 授权
auth_result = payment_method.authorize(amount, currency)
if not auth_result.get("success"):
return auth_result
# 3. 捕获
capture_result = payment_method.capture(amount, auth_result["transaction_id"])
return capture_result
一般3:支付网关抽象
class PaymentGateway(ABC):
“”“支付网关的一般化抽象”“”
@abstractmethod
def connect(self) -> bool:
"""连接网关"""
pass
@abstractmethod
def send_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
"""发送请求到网关"""
pass
@abstractmethod
def parse_response(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
"""解析网关响应"""
pass
# 通用方法
def log_transaction(self, transaction_data: Dict[str, Any]) -> None:
"""记录交易日志(通用实现)"""
print(f"Logging transaction: {transaction_data}")
一般4:支付工厂抽象
class PaymentFactory(ABC):
“”“支付工厂的一般化抽象”“”
@abstractmethod
def create_payment_method(self, method_type: str, **kwargs) -> PaymentMethod:
"""创建支付方式"""
pass
@abstractmethod
def create_processor(self, processor_type: str) -> PaymentProcessor:
"""创建支付处理器"""
pass
java
// Java - 一般化设计:使用接口和抽象类定义支付系统
package payment.system;
import java.util.Map;
// 一般1:支付方式接口
public interface PaymentMethod {
// 抽象方法
Map<String, Object> authorize(double amount, String currency);
Map<String, Object> capture(double amount, String transactionId);
Map<String, Object> refund(double amount, String transactionId);
Map<String, Object> voidTransaction(String transactionId);
// 默认方法(Java 8+)
default boolean validateAmount(double amount) {
return amount > 0 && amount <= 1_000_000; // 最大100万
}
default String getMethodName() {
return this.getClass().getSimpleName();
}
// 静态方法
static String getPaymentSystem() {
return "Payment System";
}
}
// 一般2:支付处理器抽象类(模板方法模式)
public abstract class PaymentProcessor {
// 模板方法:定义支付处理流程
public final Map<String, Object> processPayment(PaymentMethod method,
double amount,
String currency) {
// 1. 验证
if (!method.validateAmount(amount)) {
return Map.of("success", false, "error", "Invalid amount");
}
// 2. 预处理
preProcess(method, amount, currency);
// 3. 执行支付
Map<String, Object> result = executePayment(method, amount, currency);
// 4. 后处理
postProcess(result);
return result;
}
// 抽象方法:子类必须实现
protected abstract Map<String, Object> executePayment(PaymentMethod method,
double amount,
String currency);
// 钩子方法:子类可以覆盖
protected void preProcess(PaymentMethod method, double amount, String currency) {
// 默认空实现
}
protected void postProcess(Map<String, Object> result) {
// 默认空实现
}
// 抽象方法:获取支持的支付方式
public abstract List<Class<? extends PaymentMethod>> getSupportedMethods();
}
// 一般3:支付网关接口
public interface PaymentGateway {
boolean connect();
Map<String, Object> sendRequest(Map<String, Object> requestData);
Map<String, Object> parseResponse(Map<String, Object> responseData);
// 默认方法
default void logTransaction(Map<String, Object> transactionData) {
System.out.println("Logging transaction: " + transactionData);
}
}
// 一般4:支付工厂接口
public interface PaymentFactory {
PaymentMethod createPaymentMethod(String methodType, Map<String, Object> params);
PaymentProcessor createProcessor(String processorType);
// 泛型方法
default <T extends PaymentMethod> T createPaymentMethod(Class<T> type,
Map<String, Object> params) {
try {
return type.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to create payment method", e);
}
}
}
cpp
// C++ - 一般化设计:使用抽象类和模板
#include
#include
#include
// 一般1:支付方式抽象类
class PaymentMethod {
public:
virtual ~PaymentMethod() = default;
// 纯虚函数
virtual std::map<std::string, std::string> authorize(double amount,
const std::string& currency) = 0;
virtual std::map<std::string, std::string> capture(double amount,
const std::string& transactionId) = 0;
virtual std::map<std::string, std::string> refund(double amount,
const std::string& transactionId) = 0;
virtual std::map<std::string, std::string> voidTransaction(const std::string& transactionId) = 0;
// 虚函数(可以有默认实现)
virtual bool validateAmount(double amount) {
return amount > 0 && amount <= 1000000; // 最大100万
}
virtual std::string getMethodName() const {
return typeid(*this).name();
}
// 静态方法
static std::string getPaymentSystem() {
return "Payment System";
}
};
// 一般2:支付处理器抽象类(模板方法模式)
class PaymentProcessor {
public:
virtual ~PaymentProcessor() = default;
// 模板方法
std::map<std::string, std::string> processPayment(PaymentMethod* method,
double amount,
const std::string& currency) {
std::map<std::string, std::string> result;
// 1. 验证
if (!method->validateAmount(amount)) {
result["success"] = "false";
result["error"] = "Invalid amount";
return result;
}
// 2. 预处理
preProcess(method, amount, currency);
// 3. 执行支付
result = executePayment(method, amount, currency);
// 4. 后处理
postProcess(result);
return result;
}
// 抽象方法
virtual std::map<std::string, std::string> executePayment(PaymentMethod* method,
double amount,
const std::string& currency) = 0;
// 钩子方法
virtual void preProcess(PaymentMethod* method, double amount, const std::string& currency) {
// 默认空实现
}
virtual void postProcess(const std::map<std::string, std::string>& result) {
// 默认空实现
}
// 抽象方法:获取支持的支付方式
virtual std::vector<std::string> getSupportedMethods() const = 0;
};
// 一般3:支付网关抽象类
class PaymentGateway {
public:
virtual ~PaymentGateway() = default;
virtual bool connect() = 0;
virtual std::map<std::string, std::string> sendRequest(const std::map<std::string, std::string>& request) = 0;
virtual std::map<std::string, std::string> parseResponse(const std::map<std::string, std::string>& response) = 0;
virtual void logTransaction(const std::map<std::string, std::string>& transaction) {
std::cout << "Logging transaction" << std::endl;
}
};
// 一般4:支付工厂抽象类
class PaymentFactory {
public:
virtual ~PaymentFactory() = default;
virtual std::unique_ptr<PaymentMethod> createPaymentMethod(const std::string& methodType) = 0;
virtual std::unique_ptr<PaymentProcessor> createProcessor(const std::string& processorType) = 0;
// 模板方法
template<typename T>
std::unique_ptr<T> createPaymentMethod() {
return std::make_unique<T>();
}
};
// 一般5:支付策略抽象(策略模式)
class PaymentStrategy {
public:
virtual ~PaymentStrategy() = default;
virtual std::map<std::string, std::string> pay(double amount, const std::string& currency) = 0;
virtual std::map<std::string, std::string> refund(double amount, const std::string& transactionId) = 0;
virtual std::string getStrategyName() const = 0;
};
第二阶段:特殊化实现 - 提供具体支付方式
python
Python - 特殊化实现:各种具体支付方式
import time
import hashlib
from datetime import datetime
特殊1:信用卡支付(继承自PaymentMethod)
class CreditCardPayment(PaymentMethod):
“”“信用卡支付的具体实现”“”
def __init__(self, card_number: str, expiry_date: str, cvv: str):
self.card_number = self._mask_card_number(card_number)
self.expiry_date = expiry_date
self.cvv = cvv
self._gateway = CreditCardGateway()
def authorize(self, amount: float, currency: str) -> Dict[str, Any]:
print(f"信用卡授权: {amount} {currency}")
# 连接网关
if not self._gateway.connect():
return {"success": False, "error": "无法连接到支付网关"}
# 准备请求数据
request_data = {
"card_number": self.card_number,
"expiry_date": self.expiry_date,
"cvv": self.cvv,
"amount": amount,
"currency": currency,
"action": "authorize"
}
# 发送请求
response = self._gateway.send_request(request_data)
# 解析响应
return self._gateway.parse_response(response)
def capture(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"信用卡扣款: {amount}, 交易ID: {transaction_id}")
request_data = {
"transaction_id": transaction_id,
"amount": amount,
"action": "capture"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
def refund(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"信用卡退款: {amount}, 交易ID: {transaction_id}")
request_data = {
"transaction_id": transaction_id,
"amount": amount,
"action": "refund"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
def void(self, transaction_id: str) -> Dict[str, Any]:
print(f"信用卡取消交易: {transaction_id}")
request_data = {
"transaction_id": transaction_id,
"action": "void"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
# 特殊方法:信用卡特定验证
def validate_card(self) -> bool:
"""验证信用卡信息(信用卡特有的方法)"""
if not self.card_number or len(self.card_number.replace("*", "")) < 12:
return False
if not self.expiry_date or len(self.expiry_date) != 5:
return False
if not self.cvv or len(self.cvv) not in [3, 4]:
return False
return True
# 私有方法:掩码信用卡号
def _mask_card_number(self, card_number: str) -> str:
if len(card_number) < 4:
return card_number
return "**** **** **** " + card_number[-4:]
特殊2:PayPal支付
class PayPalPayment(PaymentMethod):
“”“PayPal支付的具体实现”“”
def __init__(self, email: str, token: str = None):
self.email = email
self.token = token
self._gateway = PayPalGateway()
self._session = None
def authorize(self, amount: float, currency: str) -> Dict[str, Any]:
print(f"PayPal授权: {amount} {currency}")
# 确保已连接
self._ensure_connected()
# PayPal特有的授权流程
request_data = {
"email": self.email,
"amount": amount,
"currency": currency,
"action": "authorize"
}
if self.token:
request_data["token"] = self.token
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
def capture(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"PayPal扣款: {amount}, 交易ID: {transaction_id}")
self._ensure_connected()
request_data = {
"transaction_id": transaction_id,
"amount": amount,
"action": "capture"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
def refund(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"PayPal退款: {amount}, 交易ID: {transaction_id}")
self._ensure_connected()
request_data = {
"transaction_id": transaction_id,
"amount": amount,
"action": "refund"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
def void(self, transaction_id: str) -> Dict[str, Any]:
print(f"PayPal取消交易: {transaction_id}")
self._ensure_connected()
request_data = {
"transaction_id": transaction_id,
"action": "void"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
# 特殊方法:PayPal特有的方法
def create_billing_agreement(self) -> Dict[str, Any]:
"""创建账单协议(PayPal特有)"""
self._ensure_connected()
request_data = {
"email": self.email,
"action": "create_billing_agreement"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
def _ensure_connected(self) -> None:
"""确保连接到PayPal(PayPal特有的连接逻辑)"""
if not self._session:
if not self._gateway.connect():
raise ConnectionError("无法连接到PayPal")
self._session = self._gateway.create_session(self.email)
特殊3:加密货币支付
class CryptoPayment(PaymentMethod):
“”“加密货币支付的具体实现”“”
def __init__(self, wallet_address: str, cryptocurrency: str = "BTC"):
self.wallet_address = wallet_address
self.cryptocurrency = cryptocurrency
self._gateway = CryptoGateway()
self._confirmations_needed = 3 # 需要3个确认
def authorize(self, amount: float, currency: str) -> Dict[str, Any]:
print(f"加密货币授权: {amount} {currency}")
# 加密货币不需要传统授权,而是创建支付地址
request_data = {
"wallet_address": self.wallet_address,
"cryptocurrency": self.cryptocurrency,
"amount": amount,
"currency": currency,
"action": "create_payment_address"
}
response = self._gateway.send_request(request_data)
result = self._gateway.parse_response(response)
if result["success"]:
# 加密货币交易ID就是区块链交易哈希
result["transaction_id"] = result.get("payment_address", "")
return result
def capture(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"加密货币确认: {amount}, 交易哈希: {transaction_id}")
# 检查区块链确认
request_data = {
"transaction_hash": transaction_id,
"confirmations_needed": self._confirmations_needed,
"action": "check_confirmation"
}
# 轮询检查确认(加密货币特有的流程)
max_attempts = 30
for attempt in range(max_attempts):
response = self._gateway.send_request(request_data)
result = self._gateway.parse_response(response)
if result.get("confirmed", False):
return {"success": True,
"transaction_id": transaction_id,
"confirmations": result.get("confirmations", 0)}
print(f"等待确认... ({attempt + 1}/{max_attempts})")
time.sleep(10) # 等待10秒
return {"success": False, "error": "交易确认超时"}
def refund(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"加密货币退款: {amount}, 交易哈希: {transaction_id}")
# 加密货币退款是新的交易
request_data = {
"from_address": self._gateway.get_merchant_address(),
"to_address": self.wallet_address,
"amount": amount,
"cryptocurrency": self.cryptocurrency,
"action": "send_transaction"
}
response = self._gateway.send_request(request_data)
result = self._gateway.parse_response(response)
if result["success"]:
result["refund_transaction_id"] = result["transaction_hash"]
return result
def void(self, transaction_id: str) -> Dict[str, Any]:
# 加密货币交易一旦发出就不能取消
return {"success": False, "error": "加密货币交易不可取消"}
# 特殊方法:加密货币特有的方法
def get_exchange_rate(self, fiat_currency: str) -> float:
"""获取汇率(加密货币特有)"""
request_data = {
"cryptocurrency": self.cryptocurrency,
"fiat_currency": fiat_currency,
"action": "get_exchange_rate"
}
response = self._gateway.send_request(request_data)
result = self._gateway.parse_response(response)
return float(result.get("exchange_rate", 0))
def validate_wallet_address(self) -> bool:
"""验证钱包地址(加密货币特有)"""
# 简单的格式验证
if self.cryptocurrency == "BTC":
return len(self.wallet_address) >= 26 and len(self.wallet_address) <= 35
elif self.cryptocurrency == "ETH":
return len(self.wallet_address) == 42 and self.wallet_address.startswith("0x")
else:
return len(self.wallet_address) > 0
特殊4:支付宝支付
class AlipayPayment(PaymentMethod):
“”“支付宝支付的具体实现”“”
def __init__(self, user_id: str, auth_token: str = None):
self.user_id = user_id
self.auth_token = auth_token
self._gateway = AlipayGateway()
self._qr_code = None
def authorize(self, amount: float, currency: str) -> Dict[str, Any]:
print(f"支付宝授权: {amount} {currency}")
# 支付宝特有的授权流程
request_data = {
"user_id": self.user_id,
"amount": amount,
"currency": currency,
"action": "precreate"
}
response = self._gateway.send_request(request_data)
result = self._gateway.parse_response(response)
if result["success"]:
# 保存二维码信息
self._qr_code = result.get("qr_code", "")
result["qr_code"] = self._qr_code
return result
def capture(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"支付宝扣款确认: {amount}, 交易ID: {transaction_id}")
# 支付宝通过轮询检查支付状态
request_data = {
"transaction_id": transaction_id,
"action": "query"
}
max_attempts = 30
for attempt in range(max_attempts):
response = self._gateway.send_request(request_data)
result = self._gateway.parse_response(response)
status = result.get("trade_status", "")
if status == "TRADE_SUCCESS":
return {"success": True,
"transaction_id": transaction_id,
"trade_no": result.get("trade_no", "")}
elif status == "TRADE_CLOSED":
return {"success": False, "error": "交易已关闭"}
print(f"等待支付... ({attempt + 1}/{max_attempts})")
time.sleep(2) # 等待2秒
return {"success": False, "error": "支付超时"}
def refund(self, amount: float, transaction_id: str) -> Dict[str, Any]:
print(f"支付宝退款: {amount}, 交易ID: {transaction_id}")
request_data = {
"transaction_id": transaction_id,
"amount": amount,
"action": "refund"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
def void(self, transaction_id: str) -> Dict[str, Any]:
print(f"支付宝取消交易: {transaction_id}")
request_data = {
"transaction_id": transaction_id,
"action": "cancel"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
# 特殊方法:支付宝特有的方法
def get_qr_code(self) -> str:
"""获取支付二维码(支付宝特有)"""
return self._qr_code or ""
def scan_qr_code(self, qr_code: str) -> Dict[str, Any]:
"""扫描二维码支付(支付宝特有)"""
request_data = {
"qr_code": qr_code,
"user_id": self.user_id,
"action": "scan_pay"
}
response = self._gateway.send_request(request_data)
return self._gateway.parse_response(response)
特殊5:支付处理器实现
class OnlinePaymentProcessor(PaymentProcessor):
“”“在线支付处理器的具体实现”“”
def __init__(self):
self.supported_methods = [
"CreditCardPayment",
"PayPalPayment",
"AlipayPayment"
]
def process_payment(self,
payment_method: PaymentMethod,
amount: float,
currency: str,
**kwargs) -> Dict[str, Any]:
print(f"处理在线支付: {payment_method.get_method_name()}")
# 在线支付特有的预处理
if "risk_check" in kwargs and kwargs["risk_check"]:
risk_result = self._risk_check(payment_method, amount)
if not risk_result["passed"]:
return {"success": False, "error": "风险检查失败"}
# 使用标准流程
return self.standard_payment_flow(payment_method, amount, currency)
def get_supported_methods(self) -> list:
return self.supported_methods
# 特殊方法:在线支付特有的风险检查
def _risk_check(self, payment_method: PaymentMethod, amount: float) -> Dict[str, Any]:
"""风险检查(在线支付特有)"""
# 简化的风险检查逻辑
risk_score = 0
if amount > 10000:
risk_score += 30
if isinstance(payment_method, CreditCardPayment):
risk_score += 10
elif isinstance(payment_method, CryptoPayment):
risk_score += 40
return {
"passed": risk_score < 50,
"risk_score": risk_score,
"threshold": 50
}
特殊6:加密货币支付处理器
class CryptoPaymentProcessor(PaymentProcessor):
“”“加密货币支付处理器的具体实现”“”
def __init__(self):
self.supported_methods = [
"CryptoPayment"
]
self._exchange_rate_cache = {}
def process_payment(self,
payment_method: PaymentMethod,
amount: float,
currency: str,
**kwargs) -> Dict[str, Any]:
print(f"处理加密货币支付: {payment_method.get_method_name()}")
# 加密货币特有的处理流程
if not isinstance(payment_method, CryptoPayment):
return {"success": False, "error": "不支持的支付方式"}
# 1. 验证钱包地址
if not payment_method.validate_wallet_address():
return {"success": False, "error": "无效的钱包地址"}
# 2. 获取汇率并转换金额
crypto_amount = self._convert_to_crypto(payment_method, amount, currency)
# 3. 执行加密货币特有的支付流程
auth_result = payment_method.authorize(crypto_amount, currency)
if not auth_result.get("success"):
return auth_result
# 4. 等待区块链确认
capture_result = payment_method.capture(crypto_amount, auth_result["transaction_id"])
return capture_result
def get_supported_methods(self) -> list:
return self.supported_methods
# 特殊方法:加密货币特有的转换逻辑
def _convert_to_crypto(self,
payment_method: CryptoPayment,
amount: float,
currency: str) -> float:
"""转换为加密货币金额"""
cache_key = f"{payment_method.cryptocurrency}_{currency}"
if cache_key not in self._exchange_rate_cache:
rate = payment_method.get_exchange_rate(currency)
self._exchange_rate_cache[cache_key] = rate
rate = self._exchange_rate_cache[cache_key]
crypto_amount = amount / rate if rate > 0 else 0
print(f"转换: {amount} {currency} = {crypto_amount} {payment_method.cryptocurrency}")
return crypto_amount
特殊7:支付网关实现
class CreditCardGateway(PaymentGateway):
“”“信用卡网关的具体实现”“”
def connect(self) -> bool:
print("连接到信用卡网关...")
# 模拟连接逻辑
time.sleep(0.5)
return True
def send_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
print(f"发送请求到信用卡网关: {request_data}")
# 模拟网络延迟
time.sleep(1)
# 模拟响应
transaction_id = f"CC_{int(time.time())}_{hashlib.md5(str(request_data).encode()).hexdigest()[:8]}"
return {
"success": True,
"transaction_id": transaction_id,
"status": "approved",
"timestamp": datetime.now().isoformat()
}
def parse_response(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
# 简化的响应解析
return {
"success": response_data.get("success", False),
"transaction_id": response_data.get("transaction_id", ""),
"message": response_data.get("status", "unknown")
}
特殊8:PayPal网关实现
class PayPalGateway(PaymentGateway):
“”“PayPal网关的具体实现”“”
def connect(self) -> bool:
print("连接到PayPal网关...")
time.sleep(1)
return True
def create_session(self, email: str) -> str:
"""创建PayPal会话(PayPal特有)"""
return f"PAYPAL_SESSION_{hashlib.md5(email.encode()).hexdigest()[:16]}"
def send_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
print(f"发送请求到PayPal网关: {request_data}")
time.sleep(1.5) # PayPal通常比信用卡慢
transaction_id = f"PP_{int(time.time())}_{hashlib.md5(str(request_data).encode()).hexdigest()[:8]}"
return {
"success": True,
"transaction_id": transaction_id,
"status": "completed",
"paypal_email": request_data.get("email", ""),
"timestamp": datetime.now().isoformat()
}
def parse_response(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
return {
"success": response_data.get("success", False),
"transaction_id": response_data.get("transaction_id", ""),
"message": response_data.get("status", "unknown"),
"paypal_email": response_data.get("paypal_email", "")
}
特殊9:支付工厂实现
class DefaultPaymentFactory(PaymentFactory):
“”“默认支付工厂的具体实现”“”
def create_payment_method(self, method_type: str, **kwargs) -> PaymentMethod:
method_type = method_type.lower()
if method_type == "creditcard":
return CreditCardPayment(
card_number=kwargs.get("card_number", ""),
expiry_date=kwargs.get("expiry_date", ""),
cvv=kwargs.get("cvv", "")
)
elif method_type == "paypal":
return PayPalPayment(
email=kwargs.get("email", ""),
token=kwargs.get("token", None)
)
elif method_type == "crypto":
return CryptoPayment(
wallet_address=kwargs.get("wallet_address", ""),
cryptocurrency=kwargs.get("cryptocurrency", "BTC")
)
elif method_type == "alipay":
return AlipayPayment(
user_id=kwargs.get("user_id", ""),
auth_token=kwargs.get("auth_token", None)
)
else:
raise ValueError(f"不支持的支付方式: {method_type}")
def create_processor(self, processor_type: str) -> PaymentProcessor:
processor_type = processor_type.lower()
if processor_type == "online":
return OnlinePaymentProcessor()
elif processor_type == "crypto":
return CryptoPaymentProcessor()
else:
raise ValueError(f"不支持的处理器类型: {processor_type}")
主程序:演示一般与特殊的应用
def main():
print(“=== 支付系统示例:一般与特殊的应用 ===\n”)
# 1. 创建支付工厂
factory = DefaultPaymentFactory()
# 2. 创建不同的支付方式(特殊化)
print("创建不同的支付方式:")
# 信用卡支付
credit_card = factory.create_payment_method(
"creditcard",
card_number="4111111111111111",
expiry_date="12/25",
cvv="123"
)
print(f" - {credit_card.get_method_name()}: {credit_card.card_number}")
# PayPal支付
paypal = factory.create_payment_method(
"paypal",
email="user@example.com"
)
print(f" - {paypal.get_method_name()}: {paypal.email}")
# 加密货币支付
crypto = factory.create_payment_method(
"crypto",
wallet_address="1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
cryptocurrency="BTC"
)
print(f" - {crypto.get_method_name()}: {crypto.wallet_address}")
# 3. 创建支付处理器
processor = factory.create_processor("online")
print(f"\n支付处理器支持的方式: {processor.get_supported_methods()}")
# 4. 处理支付(多态)
print("\n处理支付(多态演示):")
payment_methods = [credit_card, paypal]
amount = 100.0
currency = "USD"
for method in payment_methods:
print(f"\n使用 {method.get_method_name()} 支付 {amount} {currency}:")
result = processor.process_payment(method, amount, currency, risk_check=True)
if result["success"]:
print(f" 支付成功! 交易ID: {result.get('transaction_id', 'N/A')}")
else:
print(f" 支付失败: {result.get('error', '未知错误')}")
# 5. 演示特殊方法
print("\n特殊方法演示:")
# 信用卡特殊方法
if isinstance(credit_card, CreditCardPayment):
is_valid = credit_card.validate_card()
print(f"信用卡验证: {'通过' if is_valid else '失败'}")
# PayPal特殊方法
if isinstance(paypal, PayPalPayment):
agreement = paypal.create_billing_agreement()
print(f"PayPal账单协议: {agreement.get('agreement_id', '未创建')}")
# 加密货币特殊方法
if isinstance(crypto, CryptoPayment):
rate = crypto.get_exchange_rate("USD")
print(f"比特币汇率: 1 BTC = {rate} USD")
# 6. 演示一般接口的统一使用
print("\n一般接口的统一使用:")
# 所有支付方式都遵循相同的接口
for method in payment_methods + [crypto]:
# 调用一般方法
method_name = method.get_method_name()
is_valid = method.validate_amount(50000)
print(f"{method_name} 验证金额 50000: {'有效' if is_valid else '无效'}")
# 调用特殊方法(需要类型检查)
if hasattr(method, 'validate_card'):
print(f" - 支持信用卡验证")
if hasattr(method, 'get_exchange_rate'):
print(f" - 支持汇率查询")
if name == “main”:
main()
三、 一般与特殊的最佳实践
- 继承与组合的选择
python
何时使用继承(is-a关系),何时使用组合(has-a关系)
情况1:真正的is-a关系,使用继承
class Animal:
def speak(self):
pass
class Dog(Animal): # Dog is an Animal
def speak(self):
return “Woof!”
情况2:has-a关系或实现多个接口,使用组合
class Engine:
def start(self):
return “Engine started”
class Car:
def init(self):
self.engine = Engine() # Car has an Engine
def start(self):
return self.engine.start()
情况3:需要多继承,使用Mixin
class FlyableMixin:
def fly(self):
return “Flying”
class SwimmableMixin:
def swim(self):
return “Swimming”
class Duck(Animal, FlyableMixin, SwimmableMixin):
def speak(self):
return “Quack!”
# Duck可以飞和游泳,但不是"is a" Flyable或Swimmable
- 避免继承的陷阱
python
陷阱1:过度继承导致脆弱的基类问题
class BaseClass:
def process(self, data):
# 很多子类依赖这个实现
return data.upper()
class SubClass(BaseClass):
def process(self, data):
# 假设BaseClass的process被修改,可能破坏子类
result = super().process(data)
return result + " processed"
解决:使用组合和接口
class Processor:
def process(self, data):
return data.upper()
class DataHandler:
def init(self, processor):
self.processor = processor
def handle(self, data):
return self.processor.process(data)
陷阱2:菱形继承问题(多继承冲突)
class A:
def method(self):
return “A”
class B(A):
def method(self):
return “B”
class C(A):
def method(self):
return “C”
class D(B, C): # Python使用C3线性化解决
pass
Python中D的MRO: D -> B -> C -> A
d = D()
print(d.method()) # 输出"B"
解决:明确指定或使用Mixin
class BMixin:
def method(self):
return “B”
class CMixin:
def method(self):
return “C”
class D2(BMixin, CMixin):
def method(self):
# 明确调用哪个
return BMixin.method(self)
四、 一般与特殊的优势对比
方面 一般化的优势 特殊化的优势
代码复用 高:通用代码在父类中实现 低:特定代码无法复用
扩展性 高:通过继承容易扩展 中:需要修改具体实现
维护性 高:修改通用逻辑影响所有子类 低:需要修改每个具体类
灵活性 中:受限于继承层次 高:可以自由实现特定行为
类型安全 高:编译时类型检查 低:运行时可能出错
设计复杂度 高:需要良好设计继承层次 低:简单直接的实现
五、 实际应用建议
遵循Liskov替换原则:
子类必须能够替换父类而不影响程序正确性
子类不应该加强前置条件或减弱后置条件
优先使用组合:
"组合优于继承"是常见的设计原则
组合更灵活,更容易测试和维护
使用抽象基类定义接口:
使用ABC或Protocol定义一般接口
具体类实现这些接口
适度使用继承:
只在真正的is-a关系中使用继承
避免超过3层的继承深度
利用多态:
通过一般接口处理特殊对象
减少条件判断,提高代码可维护性
一般与特殊是面向对象设计的核心概念。良好的继承层次能够显著提高代码的复用性和可维护性,但过度或不恰当的继承会导致代码脆弱和难以维护。掌握在一般化和特殊化之间找到平衡的能力,是成为优秀软件设计师的关键。记住:面向接口编程,而非实现编程,这样可以保持系统的灵活性和可扩展性。
一般与特殊:软件设计的层次化思维方法
一、 一般与特殊方法论
1. 一般化(Generalization)
- 核心思想:从多个具体事物中抽取共同特征,形成更抽象、更通用的概念。
- 目的:建立共性模型,提高代码复用性,降低系统复杂性。
- 实现方式:
- 抽象类:定义通用接口和部分实现
- 接口/协议:定义行为契约
- 模板/泛型:参数化类型和算法
- 设计模式:提供通用解决方案
2. 特殊化(Specialization)
- 核心思想:从一般概念派生出具有特定行为或属性的具体实现。
- 目的:实现具体功能,适应特定需求,提供优化实现。
- 实现方式:
- 继承:扩展父类的功能
- 重写:覆盖父类方法
- 特化:为特定场景提供优化实现
- 具体类:提供完整实现
3. 两者关系
一般与特殊形成了层次化的设计结构:
- 一般化:向上抽象,提炼共性
- 特殊化:向下具体,实现特性
- 关系:父类(一般)定义接口和通用行为,子类(特殊)提供具体实现
二、 实例说明:游戏角色系统设计
我们将通过设计一个游戏角色系统,展示一般与特殊在软件开发中的应用。
第一阶段:一般化设计 - 定义游戏角色的通用模型
# Python - 一般化设计:定义游戏角色的通用模型
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from enum import Enum
# 一般1:游戏角色基类
class GameCharacter(ABC):
"""游戏角色的一般化抽象"""
def __init__(self, name: str, level: int = 1):
self.name = name
self.level = level
self.health = self.max_health
self.mana = self.max_mana
self.experience = 0
self.inventory = []
self.equipment = {}
self.status_effects = []
# 抽象属性:子类必须定义
@property
@abstractmethod
def max_health(self) -> int:
"""最大生命值"""
pass
@property
@abstractmethod
def max_mana(self) -> int:
"""最大魔法值"""
pass
@property
@abstractmethod
def base_attack(self) -> int:
"""基础攻击力"""
pass
@property
@abstractmethod
def base_defense(self) -> int:
"""基础防御力"""
pass
@property
@abstractmethod
def character_type(self) -> str:
"""角色类型"""
pass
# 抽象方法:子类必须实现
@abstractmethod
def attack(self, target: 'GameCharacter') -> Tuple[int, str]:
"""攻击目标,返回伤害值和描述"""
pass
@abstractmethod
def take_damage(self, damage: int, damage_type: str) -> int:
"""受到伤害,返回实际伤害值"""
pass
@abstractmethod
def level_up(self) -> None:
"""升级"""
pass
# 通用方法:所有角色都有的行为
def heal(self, amount: int) -> int:
"""治疗角色"""
if self.health <= 0:
return 0 # 已死亡无法治疗
old_health = self.health
self.health = min(self.health + amount, self.max_health)
healed = self.health - old_health
return healed
def restore_mana(self, amount: int) -> int:
"""恢复魔法值"""
old_mana = self.mana
self.mana = min(self.mana + amount, self.max_mana)
restored = self.mana - old_mana
return restored
def is_alive(self) -> bool:
"""是否存活"""
return self.health > 0
def get_status(self) -> Dict[str, any]:
"""获取角色状态"""
return {
"name": self.name,
"type": self.character_type,
"level": self.level,
"health": f"{self.health}/{self.max_health}",
"mana": f"{self.mana}/{self.max_mana}",
"experience": self.experience,
"alive": self.is_alive()
}
# 模板方法:通用升级流程
def _level_up_template(self) -> None:
"""升级模板方法"""
if self.experience >= self._experience_to_next_level():
self.level += 1
self._apply_level_up_bonus()
self.experience = 0
print(f"{self.name} 升级到 {self.level} 级!")
# 钩子方法:子类可以覆盖
def _experience_to_next_level(self) -> int:
"""计算升级所需经验(通用实现)"""
return 100 * self.level
def _apply_level_up_bonus(self) -> None:
"""应用升级奖励(通用实现)"""
self.health = self.max_health # 满血
self.mana = self.max_mana # 满魔
# 一般2:战斗单位接口
class CombatUnit(ABC):
"""战斗单位的一般化接口"""
@abstractmethod
def get_attack_power(self) -> int:
"""获取攻击力"""
pass
@abstractmethod
def get_defense_power(self) -> int:
"""获取防御力"""
pass
@abstractmethod
def get_speed(self) -> int:
"""获取速度"""
pass
@abstractmethod
def get_critical_chance(self) -> float:
"""获取暴击率"""
pass
# 一般3:技能系统抽象
class Skill(ABC):
"""技能的一般化抽象"""
def __init__(self, name: str, mana_cost: int, cooldown: int):
self.name = name
self.mana_cost = mana_cost
self.cooldown = cooldown
self.current_cooldown = 0
@abstractmethod
def execute(self, caster: GameCharacter, target: GameCharacter = None) -> Dict[str, any]:
"""执行技能"""
pass
@abstractmethod
def can_execute(self, caster: GameCharacter) -> bool:
"""是否可以执行技能"""
return caster.mana >= self.mana_cost and self.current_cooldown == 0
# 通用方法
def update_cooldown(self) -> None:
"""更新冷却时间"""
if self.current_cooldown > 0:
self.current_cooldown -= 1
def get_description(self) -> str:
"""获取技能描述"""
return f"{self.name} (消耗: {self.mana_cost} MP, 冷却: {self.cooldown} 回合)"
# 一般4:装备系统抽象
class Equipment(ABC):
"""装备的一般化抽象"""
def __init__(self, name: str, rarity: str, level_requirement: int):
self.name = name
self.rarity = rarity # 普通、稀有、史诗、传说
self.level_requirement = level_requirement
@property
@abstractmethod
def equipment_type(self) -> str:
"""装备类型:武器、防具、饰品"""
pass
@abstractmethod
def get_stats(self) -> Dict[str, int]:
"""获取装备属性"""
pass
@abstractmethod
def can_equip(self, character: GameCharacter) -> bool:
"""是否可以装备"""
return character.level >= self.level_requirement
# 一般5:AI行为抽象
class AIBehavior(ABC):
"""AI行为的一般化抽象"""
@abstractmethod
def decide_action(self, character: GameCharacter, enemies: List[GameCharacter]) -> str:
"""决定行动"""
pass
@abstractmethod
def select_target(self, character: GameCharacter, enemies: List[GameCharacter]) -> Optional[GameCharacter]:
"""选择目标"""
pass
# 通用方法
def evaluate_threat(self, enemy: GameCharacter) -> float:
"""评估威胁程度"""
# 简单的威胁评估:生命值越低,威胁越小
health_ratio = enemy.health / enemy.max_health
return 1.0 - health_ratio
# 一般6:角色工厂抽象
class CharacterFactory(ABC):
"""角色工厂的一般化抽象"""
@abstractmethod
def create_character(self, character_type: str, name: str, **kwargs) -> GameCharacter:
"""创建角色"""
pass
@abstractmethod
def create_skill(self, skill_type: str, **kwargs) -> Skill:
"""创建技能"""
pass
@abstractmethod
def create_equipment(self, equipment_type: str, **kwargs) -> Equipment:
"""创建装备"""
pass
# 一般7:伤害系统
class DamageSystem:
"""伤害计算系统(一般化实现)"""
@staticmethod
def calculate_damage(attacker: GameCharacter, defender: GameCharacter,
base_damage: int, damage_type: str = "physical") -> int:
"""计算伤害"""
# 基础伤害计算
damage = base_damage
# 暴击判定
if hasattr(attacker, 'get_critical_chance'):
critical_chance = attacker.get_critical_chance()
import random
if random.random() < critical_chance:
damage *= 2
print("暴击!")
# 防御减免
if hasattr(defender, 'get_defense_power'):
defense = defender.get_defense_power()
damage_reduction = defense * 0.01 # 每点防御减少1%伤害
damage = int(damage * (1 - min(damage_reduction, 0.7))) # 最多减少70%伤害
# 等级压制
level_difference = attacker.level - defender.level
if level_difference > 0:
damage = int(damage * (1 + level_difference * 0.05)) # 每级高5%
elif level_difference < 0:
damage = int(damage * (1 + level_difference * 0.03)) # 每级低3%
return max(1, damage) # 至少1点伤害
# 一般8:状态效果
class StatusEffect(ABC):
"""状态效果的一般化抽象"""
def __init__(self, name: str, duration: int):
self.name = name
self.duration = duration
self.remaining_duration = duration
@abstractmethod
def apply(self, target: GameCharacter) -> None:
"""应用效果"""
pass
@abstractmethod
def remove(self, target: GameCharacter) -> None:
"""移除效果"""
pass
def update(self, target: GameCharacter) -> bool:
"""更新效果,返回是否结束"""
self.remaining_duration -= 1
if self.remaining_duration <= 0:
self.remove(target)
return True
return False
// Java - 一般化设计:使用接口和抽象类定义游戏角色系统
package game.characters;
import java.util.*;
// 一般1:游戏角色抽象类
public abstract class GameCharacter {
protected String name;
protected int level;
protected int health;
protected int mana;
protected int experience;
protected List<Item> inventory;
protected Map<EquipmentSlot, Equipment> equipment;
protected List<StatusEffect> statusEffects;
public GameCharacter(String name) {
this.name = name;
this.level = 1;
this.health = getMaxHealth();
this.mana = getMaxMana();
this.experience = 0;
this.inventory = new ArrayList<>();
this.equipment = new HashMap<>();
this.statusEffects = new ArrayList<>();
}
// 抽象方法:子类必须实现
public abstract int getMaxHealth();
public abstract int getMaxMana();
public abstract int getBaseAttack();
public abstract int getBaseDefense();
public abstract String getCharacterType();
public abstract AttackResult attack(GameCharacter target);
public abstract int takeDamage(int damage, DamageType damageType);
public abstract void levelUp();
// 通用方法:所有角色都有的行为
public int heal(int amount) {
if (health <= 0) {
return 0; // 已死亡无法治疗
}
int oldHealth = health;
health = Math.min(health + amount, getMaxHealth());
int healed = health - oldHealth;
return healed;
}
public int restoreMana(int amount) {
int oldMana = mana;
mana = Math.min(mana + amount, getMaxMana());
int restored = mana - oldMana;
return restored;
}
public boolean isAlive() {
return health > 0;
}
public CharacterStatus getStatus() {
return new CharacterStatus(
name,
getCharacterType(),
level,
health,
getMaxHealth(),
mana,
getMaxMana(),
experience,
isAlive()
);
}
// 模板方法:通用升级流程
protected final void levelUpTemplate() {
if (experience >= getExperienceToNextLevel()) {
level++;
applyLevelUpBonus();
experience = 0;
System.out.println(name + " 升级到 " + level + " 级!");
}
}
// 钩子方法:子类可以覆盖
protected int getExperienceToNextLevel() {
return 100 * level;
}
protected void applyLevelUpBonus() {
health = getMaxHealth(); // 满血
mana = getMaxMana(); // 满魔
}
// 访问器方法
public String getName() { return name; }
public int getLevel() { return level; }
public int getHealth() { return health; }
public int getMana() { return mana; }
public int getExperience() { return experience; }
public void addExperience(int exp) {
this.experience += exp;
levelUpTemplate();
}
}
// 一般2:战斗单位接口
public interface CombatUnit {
int getAttackPower();
int getDefensePower();
int getSpeed();
double getCriticalChance();
}
// 一般3:技能接口
public interface Skill {
String getName();
int getManaCost();
int getCooldown();
SkillResult execute(GameCharacter caster, GameCharacter target);
boolean canExecute(GameCharacter caster);
// 默认方法
default void updateCooldown() {
// 更新冷却时间逻辑
}
default String getDescription() {
return getName() + " (消耗: " + getManaCost() + " MP, 冷却: " + getCooldown() + " 回合)";
}
}
// 一般4:装备抽象类
public abstract class Equipment {
protected String name;
protected Rarity rarity;
protected int levelRequirement;
public Equipment(String name, Rarity rarity, int levelRequirement) {
this.name = name;
this.rarity = rarity;
this.levelRequirement = levelRequirement;
}
public abstract EquipmentType getEquipmentType();
public abstract Map<StatType, Integer> getStats();
public abstract boolean canEquip(GameCharacter character);
// 枚举
public enum Rarity {
COMMON, UNCOMMON, RARE, EPIC, LEGENDARY
}
public enum EquipmentType {
WEAPON, ARMOR, HELMET, GLOVES, BOOTS, ACCESSORY
}
public enum StatType {
HEALTH, MANA, ATTACK, DEFENSE, SPEED, CRITICAL_CHANCE
}
}
// 一般5:AI行为接口
public interface AIBehavior {
String decideAction(GameCharacter character, List<GameCharacter> enemies);
GameCharacter selectTarget(GameCharacter character, List<GameCharacter> enemies);
// 默认方法
default double evaluateThreat(GameCharacter enemy) {
double healthRatio = (double) enemy.getHealth() / enemy.getMaxHealth();
return 1.0 - healthRatio;
}
}
// 一般6:角色工厂接口
public interface CharacterFactory {
GameCharacter createCharacter(String characterType, String name, Map<String, Object> params);
Skill createSkill(String skillType, Map<String, Object> params);
Equipment createEquipment(String equipmentType, Map<String, Object> params);
}
// 一般7:攻击结果记录类
public class AttackResult {
private final int damage;
private final boolean critical;
private final String message;
public AttackResult(int damage, boolean critical, String message) {
this.damage = damage;
this.critical = critical;
this.message = message;
}
// getter方法
public int getDamage() { return damage; }
public boolean isCritical() { return critical; }
public String getMessage() { return message; }
}
// 一般8:角色状态记录类
public class CharacterStatus {
private final String name;
private final String type;
private final int level;
private final int currentHealth;
private final int maxHealth;
private final int currentMana;
private final int maxMana;
private final int experience;
private final boolean alive;
public CharacterStatus(String name, String type, int level,
int currentHealth, int maxHealth,
int currentMana, int maxMana,
int experience, boolean alive) {
this.name = name;
this.type = type;
this.level = level;
this.currentHealth = currentHealth;
this.maxHealth = maxHealth;
this.currentMana = currentMana;
this.maxMana = maxMana;
this.experience = experience;
this.alive = alive;
}
@Override
public String toString() {
return String.format("%s [%s] Lv.%d HP:%d/%d MP:%d/%d EXP:%d %s",
name, type, level, currentHealth, maxHealth,
currentMana, maxMana, experience, alive ? "存活" : "死亡");
}
}
// C++ - 一般化设计:使用抽象类和模板定义游戏角色系统
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <functional>
// 一般1:游戏角色抽象类
class GameCharacter {
protected:
std::string name;
int level;
int health;
int mana;
int experience;
std::vector<std::shared_ptr<class Item>> inventory;
std::map<std::string, std::shared_ptr<class Equipment>> equipment;
std::vector<std::shared_ptr<class StatusEffect>> statusEffects;
public:
GameCharacter(const std::string& name)
: name(name), level(1), health(0), mana(0), experience(0) {
health = getMaxHealth();
mana = getMaxMana();
}
virtual ~GameCharacter() = default;
// 纯虚函数:子类必须实现
virtual int getMaxHealth() const = 0;
virtual int getMaxMana() const = 0;
virtual int getBaseAttack() const = 0;
virtual int getBaseDefense() const = 0;
virtual std::string getCharacterType() const = 0;
virtual struct AttackResult attack(GameCharacter* target) = 0;
virtual int takeDamage(int damage, const std::string& damageType) = 0;
virtual void levelUp() = 0;
// 通用方法:所有角色都有的行为
int heal(int amount) {
if (health <= 0) {
return 0; // 已死亡无法治疗
}
int oldHealth = health;
health = std::min(health + amount, getMaxHealth());
int healed = health - oldHealth;
return healed;
}
int restoreMana(int amount) {
int oldMana = mana;
mana = std::min(mana + amount, getMaxMana());
int restored = mana - oldMana;
return restored;
}
bool isAlive() const {
return health > 0;
}
struct CharacterStatus getStatus() const {
return {
name,
getCharacterType(),
level,
health,
getMaxHealth(),
mana,
getMaxMana(),
experience,
isAlive()
};
}
// 模板方法:通用升级流程
void levelUpTemplate() {
if (experience >= getExperienceToNextLevel()) {
level++;
applyLevelUpBonus();
experience = 0;
std::cout << name << " 升级到 " << level << " 级!" << std::endl;
}
}
// 钩子方法:子类可以覆盖
virtual int getExperienceToNextLevel() const {
return 100 * level;
}
virtual void applyLevelUpBonus() {
health = getMaxHealth(); // 满血
mana = getMaxMana(); // 满魔
}
// 访问器方法
std::string getName() const { return name; }
int getLevel() const { return level; }
int getHealth() const { return health; }
int getMana() const { return mana; }
int getExperience() const { return experience; }
void addExperience(int exp) {
this->experience += exp;
levelUpTemplate();
}
};
// 一般2:战斗单位接口
class CombatUnit {
public:
virtual ~CombatUnit() = default;
virtual int getAttackPower() const = 0;
virtual int getDefensePower() const = 0;
virtual int getSpeed() const = 0;
virtual double getCriticalChance() const = 0;
};
// 一般3:技能抽象类
class Skill {
protected:
std::string name;
int manaCost;
int cooldown;
int currentCooldown;
public:
Skill(const std::string& name, int manaCost, int cooldown)
: name(name), manaCost(manaCost), cooldown(cooldown), currentCooldown(0) {}
virtual ~Skill() = default;
virtual struct SkillResult execute(GameCharacter* caster, GameCharacter* target = nullptr) = 0;
virtual bool canExecute(GameCharacter* caster) const {
return caster->getMana() >= manaCost && currentCooldown == 0;
}
// 通用方法
void updateCooldown() {
if (currentCooldown > 0) {
currentCooldown--;
}
}
std::string getDescription() const {
return name + " (消耗: " + std::to_string(manaCost) +
" MP, 冷却: " + std::to_string(cooldown) + " 回合)";
}
std::string getName() const { return name; }
int getManaCost() const { return manaCost; }
int getCooldown() const { return cooldown; }
};
// 一般4:装备抽象类
class Equipment {
public:
enum class Rarity {
COMMON, UNCOMMON, RARE, EPIC, LEGENDARY
};
enum class EquipmentType {
WEAPON, ARMOR, HELMET, GLOVES, BOOTS, ACCESSORY
};
protected:
std::string name;
Rarity rarity;
int levelRequirement;
public:
Equipment(const std::string& name, Rarity rarity, int levelRequirement)
: name(name), rarity(rarity), levelRequirement(levelRequirement) {}
virtual ~Equipment() = default;
virtual EquipmentType getEquipmentType() const = 0;
virtual std::map<std::string, int> getStats() const = 0;
virtual bool canEquip(GameCharacter* character) const {
return character->getLevel() >= levelRequirement;
}
std::string getName() const { return name; }
Rarity getRarity() const { return rarity; }
int getLevelRequirement() const { return levelRequirement; }
};
// 一般5:AI行为抽象类
class AIBehavior {
public:
virtual ~AIBehavior() = default;
virtual std::string decideAction(GameCharacter* character,
const std::vector<GameCharacter*>& enemies) = 0;
virtual GameCharacter* selectTarget(GameCharacter* character,
const std::vector<GameCharacter*>& enemies) = 0;
// 通用方法
virtual double evaluateThreat(GameCharacter* enemy) const {
double healthRatio = static_cast<double>(enemy->getHealth()) / enemy->getMaxHealth();
return 1.0 - healthRatio;
}
};
// 一般6:角色工厂抽象类
class CharacterFactory {
public:
virtual ~CharacterFactory() = default;
virtual std::unique_ptr<GameCharacter> createCharacter(const std::string& characterType,
const std::string& name,
const std::map<std::string, std::string>& params) = 0;
virtual std::unique_ptr<Skill> createSkill(const std::string& skillType,
const std::map<std::string, std::string>& params) = 0;
virtual std::unique_ptr<Equipment> createEquipment(const std::string& equipmentType,
const std::map<std::string, std::string>& params) = 0;
// 模板方法
template<typename T>
std::unique_ptr<T> create() {
return std::make_unique<T>();
}
};
// 一般7:数据结构
struct AttackResult {
int damage;
bool critical;
std::string message;
AttackResult(int dmg, bool crit, const std::string& msg)
: damage(dmg), critical(crit), message(msg) {}
};
struct SkillResult {
bool success;
std::string message;
int damage;
int healing;
SkillResult(bool succ, const std::string& msg, int dmg = 0, int heal = 0)
: success(succ), message(msg), damage(dmg), healing(heal) {}
};
struct CharacterStatus {
std::string name;
std::string type;
int level;
int currentHealth;
int maxHealth;
int currentMana;
int maxMana;
int experience;
bool alive;
std::string toString() const {
return name + " [" + type + "] Lv." + std::to_string(level) +
" HP:" + std::to_string(currentHealth) + "/" + std::to_string(maxHealth) +
" MP:" + std::to_string(currentMana) + "/" + std::to_string(maxMana) +
" EXP:" + std::to_string(experience) + " " + (alive ? "存活" : "死亡");
}
};
// 一般8:伤害系统
class DamageSystem {
public:
static int calculateDamage(GameCharacter* attacker, GameCharacter* defender,
int baseDamage, const std::string& damageType = "physical") {
int damage = baseDamage;
// 暴击判定
if (auto combatUnit = dynamic_cast<CombatUnit*>(attacker)) {
double criticalChance = combatUnit->getCriticalChance();
if (rand() / static_cast<double>(RAND_MAX) < criticalChance) {
damage *= 2;
std::cout << "暴击!" << std::endl;
}
}
// 防御减免
if (auto combatUnit = dynamic_cast<CombatUnit*>(defender)) {
int defense = combatUnit->getDefensePower();
double damageReduction = defense * 0.01; // 每点防御减少1%伤害
damage = static_cast<int>(damage * (1 - std::min(damageReduction, 0.7))); // 最多减少70%伤害
}
// 等级压制
int levelDifference = attacker->getLevel() - defender->getLevel();
if (levelDifference > 0) {
damage = static_cast<int>(damage * (1 + levelDifference * 0.05)); // 每级高5%
} else if (levelDifference < 0) {
damage = static_cast<int>(damage * (1 + levelDifference * 0.03)); // 每级低3%
}
return std::max(1, damage); // 至少1点伤害
}
};
第二阶段:特殊化实现 - 各种具体游戏角色
# Python - 特殊化实现:各种具体游戏角色
import random
from enum import Enum
from typing import Dict, List, Tuple
# 特殊1:战士职业
class Warrior(GameCharacter, CombatUnit):
"""战士职业的具体实现"""
def __init__(self, name: str, level: int = 1):
super().__init__(name, level)
self.rage = 0 # 战士特有:怒气值
self.max_rage = 100
self.strength = 10 + level * 2 # 力量属性
@property
def max_health(self) -> int:
"""战士生命值较高"""
return 100 + self.level * 20 + self.strength * 5
@property
def max_mana(self) -> int:
"""战士魔法值较低"""
return 30 + self.level * 5
@property
def base_attack(self) -> int:
"""战士攻击力较高"""
return 15 + self.level * 3 + self.strength * 2
@property
def base_defense(self) -> int:
"""战士防御力高"""
return 10 + self.level * 2 + self.strength
@property
def character_type(self) -> str:
return "战士"
# 战斗单位接口实现
def get_attack_power(self) -> int:
return self.base_attack + self.rage // 10 # 怒气增加攻击力
def get_defense_power(self) -> int:
return self.base_defense + self.level * 2
def get_speed(self) -> int:
return 50 + self.level * 1 # 战士速度较慢
def get_critical_chance(self) -> float:
return 0.05 + self.level * 0.01 # 基础暴击率5%,每级+1%
# 特殊方法:战士特有的攻击
def attack(self, target: GameCharacter) -> Tuple[int, str]:
"""战士攻击:造成物理伤害并积累怒气"""
if not self.is_alive():
return 0, "战士已死亡,无法攻击"
# 计算基础伤害
base_damage = self.get_attack_power()
# 使用伤害系统计算最终伤害
damage = DamageSystem.calculate_damage(self, target, base_damage, "physical")
# 对目标造成伤害
actual_damage = target.take_damage(damage, "physical")
# 积累怒气
self.rage = min(self.rage + 10, self.max_rage)
message = f"{self.name} 对 {target.name} 造成 {actual_damage} 点物理伤害!"
if actual_damage != damage:
message += f" (格挡了 {damage - actual_damage} 点伤害)"
return actual_damage, message
def take_damage(self, damage: int, damage_type: str) -> int:
"""战士受到伤害:有几率格挡"""
if damage_type == "physical":
# 战士有几率格挡物理伤害
block_chance = 0.1 + self.level * 0.01 # 基础10%,每级+1%
if random.random() < block_chance:
blocked_damage = damage // 2
actual_damage = damage - blocked_damage
print(f"{self.name} 格挡了 {blocked_damage} 点伤害!")
else:
actual_damage = damage
else:
actual_damage = damage
# 受到伤害增加怒气
self.rage = min(self.rage + actual_damage, self.max_rage)
# 减少生命值
self.health = max(0, self.health - actual_damage)
return actual_damage
def level_up(self) -> None:
"""战士升级:增加力量属性"""
self.level += 1
self.strength += 2
self.health = self.max_health
self.mana = self.max_mana
print(f"{self.name} 升级到 {self.level} 级!力量提升到 {self.strength}")
# 战士特有方法
def use_rage_skill(self, target: GameCharacter) -> Tuple[int, str]:
"""使用怒气技能(战士特有)"""
if self.rage < 50:
return 0, "怒气不足!"
skill_name = "旋风斩" if self.rage >= 80 else "猛击"
rage_cost = 80 if self.rage >= 80 else 50
# 计算伤害
base_damage = self.base_attack * (2 if self.rage >= 80 else 1.5)
damage = DamageSystem.calculate_damage(self, target, base_damage, "physical")
actual_damage = target.take_damage(damage, "physical")
self.rage -= rage_cost
message = f"{self.name} 使用 {skill_name} 对 {target.name} 造成 {actual_damage} 点伤害!"
return actual_damage, message
def get_status(self) -> Dict[str, any]:
"""获取战士特有状态"""
status = super().get_status()
status["rage"] = f"{self.rage}/{self.max_rage}"
status["strength"] = self.strength
return status
# 特殊2:法师职业
class Mage(GameCharacter, CombatUnit):
"""法师职业的具体实现"""
def __init__(self, name: str, level: int = 1):
super().__init__(name, level)
self.intelligence = 10 + level * 3 # 智力属性
self.spells = [] # 法师特有:法术列表
@property
def max_health(self) -> int:
"""法师生命值较低"""
return 60 + self.level * 10 + self.intelligence
@property
def max_mana(self) -> int:
"""法师魔法值很高"""
return 100 + self.level * 20 + self.intelligence * 3
@property
def base_attack(self) -> int:
"""法师基础攻击力低"""
return 8 + self.level * 1
@property
def base_defense(self) -> int:
"""法师防御力低"""
return 5 + self.level * 1
@property
def character_type(self) -> str:
return "法师"
# 战斗单位接口实现
def get_attack_power(self) -> int:
return self.base_attack + self.intelligence # 智力增加攻击力
def get_defense_power(self) -> int:
return self.base_defense + self.intelligence // 2 # 智力增加少量防御
def get_speed(self) -> int:
return 60 + self.level * 2 # 法师速度中等
def get_critical_chance(self) -> float:
return 0.1 + self.level * 0.02 # 基础暴击率10%,每级+2%
# 特殊方法:法师攻击(使用魔法)
def attack(self, target: GameCharacter) -> Tuple[int, str]:
"""法师攻击:使用魔法造成伤害"""
if not self.is_alive():
return 0, "法师已死亡,无法攻击"
# 检查魔法值
if self.mana < 10:
# 魔法不足时使用物理攻击
return self._physical_attack(target)
# 使用魔法攻击
spell_cost = 10
base_damage = self.intelligence * 2
damage = DamageSystem.calculate_damage(self, target, base_damage, "magical")
actual_damage = target.take_damage(damage, "magical")
self.mana -= spell_cost
message = f"{self.name} 对 {target.name} 释放魔法,造成 {actual_damage} 点魔法伤害!"
return actual_damage, message
def _physical_attack(self, target: GameCharacter) -> Tuple[int, str]:
"""物理攻击(魔法不足时使用)"""
base_damage = self.base_attack
damage = DamageSystem.calculate_damage(self, target, base_damage, "physical")
actual_damage = target.take_damage(damage, "physical")
message = f"{self.name} 用魔杖敲击 {target.name},造成 {actual_damage} 点物理伤害!"
return actual_damage, message
def take_damage(self, damage: int, damage_type: str) -> int:
"""法师受到伤害:魔法伤害减免"""
if damage_type == "magical":
# 法师对魔法伤害有抗性
resistance = self.intelligence * 0.02 # 每点智力减少2%魔法伤害
actual_damage = int(damage * (1 - min(resistance, 0.5))) # 最多减少50%
else:
actual_damage = damage
self.health = max(0, self.health - actual_damage)
# 受到伤害时恢复少量魔法(法师特有)
if self.is_alive():
self.mana = min(self.mana + 5, self.max_mana)
return actual_damage
def level_up(self) -> None:
"""法师升级:增加智力属性"""
self.level += 1
self.intelligence += 3
self.health = self.max_health
self.mana = self.max_mana
print(f"{self.name} 升级到 {self.level} 级!智力提升到 {self.intelligence}")
# 法师特有方法
def learn_spell(self, spell: Skill) -> None:
"""学习法术(法师特有)"""
self.spells.append(spell)
print(f"{self.name} 学会了 {spell.name}!")
def cast_spell(self, spell_name: str, target: GameCharacter = None) -> Dict[str, any]:
"""施放法术(法师特有)"""
for spell in self.spells:
if spell.name == spell_name:
if spell.can_execute(self):
result = spell.execute(self, target)
return result
else:
return {"success": False, "message": "无法施放法术"}
return {"success": False, "message": f"未学会法术 {spell_name}"}
def meditate(self) -> Dict[str, any]:
"""冥想:快速恢复魔法(法师特有)"""
if not self.is_alive():
return {"success": False, "message": "已死亡,无法冥想"}
restored = self.restore_mana(self.max_mana // 2)
return {
"success": True,
"message": f"{self.name} 冥想恢复了 {restored} 点魔法值",
"mana_restored": restored
}
# 特殊3:弓箭手职业
class Archer(GameCharacter, CombatUnit):
"""弓箭手职业的具体实现"""
def __init__(self, name: str, level: int = 1):
super().__init__(name, level)
self.dexterity = 10 + level * 3 # 敏捷属性
self.arrows = 20 # 弓箭手特有:箭矢数量
self.max_arrows = 20
@property
def max_health(self) -> int:
"""弓箭手生命值中等"""
return 80 + self.level * 15 + self.dexterity
@property
def max_mana(self) -> int:
"""弓箭手魔法值中等"""
return 50 + self.level * 10 + self.dexterity
@property
def base_attack(self) -> int:
"""弓箭手攻击力高"""
return 12 + self.level * 2 + self.dexterity
@property
def base_defense(self) -> int:
"""弓箭手防御力低"""
return 6 + self.level * 1
@property
def character_type(self) -> str:
return "弓箭手"
# 战斗单位接口实现
def get_attack_power(self) -> int:
return self.base_attack + self.dexterity // 2
def get_defense_power(self) -> int:
return self.base_defense + self.dexterity // 4
def get_speed(self) -> int:
return 80 + self.level * 3 + self.dexterity # 弓箭手速度很快
def get_critical_chance(self) -> float:
return 0.15 + self.level * 0.02 + self.dexterity * 0.001 # 基础暴击率15%
# 特殊方法:弓箭手攻击(远程)
def attack(self, target: GameCharacter) -> Tuple[int, str]:
"""弓箭手攻击:远程射击"""
if not self.is_alive():
return 0, "弓箭手已死亡,无法攻击"
if self.arrows <= 0:
return self._melee_attack(target)
# 使用弓箭攻击
self.arrows -= 1
# 计算伤害,敏捷加成
base_damage = self.base_attack + self.dexterity
damage = DamageSystem.calculate_damage(self, target, base_damage, "piercing")
# 弓箭手有额外暴击率
if random.random() < 0.1: # 额外10%暴击率
damage *= 2
print("精准射击!")
actual_damage = target.take_damage(damage, "piercing")
message = f"{self.name} 射中 {target.name},造成 {actual_damage} 点穿刺伤害!"
message += f" (剩余箭矢: {self.arrows}/{self.max_arrows})"
return actual_damage, message
def _melee_attack(self, target: GameCharacter) -> Tuple[int, str]:
"""近战攻击(箭矢用完时使用)"""
base_damage = self.base_attack // 2 # 近战伤害减半
damage = DamageSystem.calculate_damage(self, target, base_damage, "physical")
actual_damage = target.take_damage(damage, "physical")
message = f"{self.name} 用匕首攻击 {target.name},造成 {actual_damage} 点物理伤害!"
return actual_damage, message
def take_damage(self, damage: int, damage_type: str) -> int:
"""弓箭手受到伤害:有几率闪避"""
# 弓箭手有闪避几率
dodge_chance = 0.1 + self.dexterity * 0.001 # 基础10%,每点敏捷+0.1%
if random.random() < dodge_chance:
print(f"{self.name} 闪避了攻击!")
return 0
self.health = max(0, self.health - damage)
return damage
def level_up(self) -> None:
"""弓箭手升级:增加敏捷属性"""
self.level += 1
self.dexterity += 3
self.health = self.max_health
self.mana = self.max_mana
self.arrows = self.max_arrows # 箭矢补满
print(f"{self.name} 升级到 {self.level} 级!敏捷提升到 {self.dexterity}")
# 弓箭手特有方法
def replenish_arrows(self, amount: int) -> None:
"""补充箭矢(弓箭手特有)"""
self.arrows = min(self.arrows + amount, self.max_arrows)
print(f"{self.name} 补充了 {amount} 支箭矢,现在有 {self.arrows} 支")
def multi_shot(self, targets: List[GameCharacter]) -> Dict[str, any]:
"""多重射击:攻击多个目标(弓箭手特有)"""
if self.arrows < 3:
return {"success": False, "message": "箭矢不足!"}
if len(targets) < 2:
return {"success": False, "message": "需要至少2个目标"}
self.arrows -= 3
results = []
for target in targets[:3]: # 最多攻击3个目标
if target.is_alive():
damage, message = self.attack(target)
results.append({
"target": target.name,
"damage": damage,
"message": message
})
return {
"success": True,
"message": f"{self.name} 使用了多重射击!",
"results": results,
"arrows_used": 3
}
# 特殊4:治疗者职业
class Healer(GameCharacter, CombatUnit):
"""治疗者职业的具体实现"""
def __init__(self, name: str, level: int = 1):
super().__init__(name, level)
self.wisdom = 10 + level * 2 # 智慧属性
self.faith = 50 # 治疗者特有:信仰值
self.max_faith = 100
@property
def max_health(self) -> int:
"""治疗者生命值中等"""
return 70 + self.level * 15 + self.wisdom * 2
@property
def max_mana(self) -> int:
"""治疗者魔法值高"""
return 80 + self.level * 15 + self.wisdom * 3
@property
def base_attack(self) -> int:
"""治疗者攻击力低"""
return 6 + self.level * 1
@property
def base_defense(self) -> int:
"""治疗者防御力中等"""
return 8 + self.level * 2 + self.wisdom
@property
def character_type(self) -> str:
return "治疗者"
# 战斗单位接口实现
def get_attack_power(self) -> int:
return self.base_attack + self.wisdom // 3
def get_defense_power(self) -> int:
return self.base_defense + self.wisdom // 2
def get_speed(self) -> int:
return 55 + self.level * 1 # 治疗者速度较慢
def get_critical_chance(self) -> float:
return 0.03 + self.level * 0.01 # 基础暴击率3%
# 特殊方法:治疗者攻击(神圣伤害)
def attack(self, target: GameCharacter) -> Tuple[int, str]:
"""治疗者攻击:神圣打击"""
if not self.is_alive():
return 0, "治疗者已死亡,无法攻击"
# 神圣伤害对亡灵有加成
damage_type = "holy"
base_damage = self.base_attack + self.wisdom
# 对亡灵敌人有额外伤害
if hasattr(target, 'character_type') and '亡灵' in target.character_type:
base_damage *= 2
damage = DamageSystem.calculate_damage(self, target, base_damage, damage_type)
actual_damage = target.take_damage(damage, damage_type)
# 攻击恢复少量信仰
self.faith = min(self.faith + 5, self.max_faith)
message = f"{self.name} 的神圣打击对 {target.name} 造成 {actual_damage} 点神圣伤害!"
return actual_damage, message
def take_damage(self, damage: int, damage_type: str) -> int:
"""治疗者受到伤害:神圣抗性"""
if damage_type == "holy":
# 治疗者对神圣伤害有抗性
actual_damage = damage // 2
else:
actual_damage = damage
self.health = max(0, self.health - actual_damage)
# 受到伤害时恢复信仰
self.faith = min(self.faith + actual_damage // 2, self.max_faith)
return actual_damage
def level_up(self) -> None:
"""治疗者升级:增加智慧属性"""
self.level += 1
self.wisdom += 2
self.health = self.max_health
self.mana = self.max_mana
self.faith = self.max_faith # 信仰补满
print(f"{self.name} 升级到 {self.level} 级!智慧提升到 {self.wisdom}")
# 治疗者特有方法
def heal_ally(self, target: GameCharacter) -> Dict[str, any]:
"""治疗盟友(治疗者特有)"""
if not self.is_alive():
return {"success": False, "message": "治疗者已死亡"}
if self.mana < 20:
return {"success": False, "message": "魔法值不足"}
mana_cost = 20
heal_amount = self.wisdom * 3 + self.level * 5
# 消耗魔法
self.mana -= mana_cost
# 治疗目标
healed = target.heal(heal_amount)
# 恢复信仰
self.faith = min(self.faith + healed // 2, self.max_faith)
return {
"success": True,
"message": f"{self.name} 治疗了 {target.name},恢复了 {healed} 点生命值",
"healed": healed,
"mana_cost": mana_cost
}
def resurrect(self, target: GameCharacter) -> Dict[str, any]:
"""复活队友(治疗者特有)"""
if not self.is_alive():
return {"success": False, "message": "治疗者已死亡"}
if self.faith < 80:
return {"success": False, "message": "信仰不足"}
if target.is_alive():
return {"success": False, "message": "目标仍然存活"}
# 消耗信仰
self.faith -= 80
# 复活目标,恢复50%生命值
target.health = target.max_health // 2
target.mana = target.max_mana // 2
return {
"success": True,
"message": f"{self.name} 复活了 {target.name}!",
"faith_cost": 80,
"target_health": target.health
}
# 特殊5:怪物类
class Monster(GameCharacter, CombatUnit):
"""怪物的一般实现"""
def __init__(self, name: str, monster_type: str, level: int = 1):
super().__init__(name, level)
self.monster_type = monster_type
self.ai_behavior = AggressiveAI() # 默认使用攻击性AI
@property
def max_health(self) -> int:
"""怪物生命值:根据类型不同"""
if self.monster_type == "goblin":
return 50 + self.level * 10
elif self.monster_type == "orc":
return 100 + self.level * 20
elif self.monster_type == "dragon":
return 300 + self.level * 50
else:
return 80 + self.level * 15
@property
def max_mana(self) -> int:
"""怪物魔法值:根据类型不同"""
if self.monster_type == "mage":
return 80 + self.level * 15
else:
return 30 + self.level * 5
@property
def base_attack(self) -> int:
"""怪物攻击力:根据类型不同"""
if self.monster_type == "goblin":
return 10 + self.level * 2
elif self.monster_type == "orc":
return 20 + self.level * 4
elif self.monster_type == "dragon":
return 40 + self.level * 8
else:
return 15 + self.level * 3
@property
def base_defense(self) -> int:
"""怪物防御力:根据类型不同"""
if self.monster_type == "goblin":
return 5 + self.level * 1
elif self.monster_type == "orc":
return 15 + self.level * 3
elif self.monster_type == "dragon":
return 25 + self.level * 5
else:
return 10 + self.level * 2
@property
def character_type(self) -> str:
return f"怪物({self.monster_type})"
# 战斗单位接口实现
def get_attack_power(self) -> int:
return self.base_attack
def get_defense_power(self) -> int:
return self.base_defense
def get_speed(self) -> int:
if self.monster_type == "goblin":
return 70 + self.level * 2
elif self.monster_type == "dragon":
return 40 + self.level * 1
else:
return 50 + self.level * 1
def get_critical_chance(self) -> float:
if self.monster_type == "assassin":
return 0.2 + self.level * 0.02
else:
return 0.05 + self.level * 0.01
def attack(self, target: GameCharacter) -> Tuple[int, str]:
"""怪物攻击:根据AI决定行动"""
action = self.ai_behavior.decide_action(self, [target])
if action == "attack":
base_damage = self.get_attack_power()
damage_type = self._get_damage_type()
damage = DamageSystem.calculate_damage(self, target, base_damage, damage_type)
actual_damage = target.take_damage(damage, damage_type)
message = f"{self.name} 攻击了 {target.name},造成 {actual_damage} 点伤害!"
return actual_damage, message
elif action == "skill":
# 使用特殊技能
return self._use_special_skill(target)
else:
return 0, f"{self.name} 没有行动"
def take_damage(self, damage: int, damage_type: str) -> int:
"""怪物受到伤害"""
actual_damage = damage
self.health = max(0, self.health - actual_damage)
return actual_damage
def level_up(self) -> None:
"""怪物升级"""
self.level += 1
self.health = self.max_health
self.mana = self.max_mana
print(f"{self.name} 升级到 {self.level} 级!")
# 怪物特有方法
def _get_damage_type(self) -> str:
"""获取伤害类型(怪物特有)"""
if self.monster_type == "dragon":
return random.choice(["fire", "physical"])
elif self.monster_type == "mage":
return "magical"
else:
return "physical"
def _use_special_skill(self, target: GameCharacter) -> Tuple[int, str]:
"""使用特殊技能(怪物特有)"""
if self.monster_type == "dragon":
# 龙息攻击
base_damage = self.base_attack * 2
damage = DamageSystem.calculate_damage(self, target, base_damage, "fire")
actual_damage = target.take_damage(damage, "fire")
message = f"{self.name} 喷出火焰,对 {target.name} 造成 {actual_damage} 点火焰伤害!"
return actual_damage, message
elif self.monster_type == "mage":
# 魔法攻击
if self.mana >= 30:
self.mana -= 30
base_damage = self.base_attack * 3
damage = DamageSystem.calculate_damage(self, target, base_damage, "magical")
actual_damage = target.take_damage(damage, "magical")
message = f"{self.name} 释放强力魔法,对 {target.name} 造成 {actual_damage} 点魔法伤害!"
return actual_damage, message
# 默认攻击
return self.attack(target)
# 特殊6:AI行为实现
class AggressiveAI(AIBehavior):
"""攻击性AI的具体实现"""
def decide_action(self, character: GameCharacter, enemies: List[GameCharacter]) -> str:
"""决定行动:总是攻击"""
return "attack"
def select_target(self, character: GameCharacter, enemies: List[GameCharacter]) -> GameCharacter:
"""选择目标:选择生命值最低的敌人"""
alive_enemies = [e for e in enemies if e.is_alive()]
if not alive_enemies:
return None
# 选择生命值最低的敌人
return min(alive_enemies, key=lambda e: e.health / e.max_health)
class DefensiveAI(AIBehavior):
"""防御性AI的具体实现"""
def decide_action(self, character: GameCharacter, enemies: List[GameCharacter]) -> str:
"""决定行动:根据生命值决定"""
health_ratio = character.health / character.max_health
if health_ratio < 0.3:
return "defend" # 防御
elif health_ratio < 0.5 and hasattr(character, 'heal_self'):
return "heal" # 治疗
else:
return "attack"
def select_target(self, character: GameCharacter, enemies: List[GameCharacter]) -> GameCharacter:
"""选择目标:选择威胁最大的敌人"""
alive_enemies = [e for e in enemies if e.is_alive()]
if not alive_enemies:
return None
# 选择威胁最大的敌人(评估威胁)
return max(alive_enemies, key=lambda e: self.evaluate_threat(e))
# 特殊7:技能实现
class FireballSkill(Skill):
"""火球术技能的具体实现"""
def __init__(self):
super().__init__("火球术", mana_cost=30, cooldown=3)
def execute(self, caster: GameCharacter, target: GameCharacter = None) -> Dict[str, any]:
"""执行火球术"""
if not caster.is_alive():
return {"success": False, "message": "施法者已死亡"}
if not self.can_execute(caster):
return {"success": False, "message": "无法施放火球术"}
if not target:
return {"success": False, "message": "需要指定目标"}
# 消耗魔法
caster.mana -= self.mana_cost
self.current_cooldown = self.cooldown
# 计算伤害
base_damage = 50
if hasattr(caster, 'intelligence'):
base_damage += caster.intelligence * 2
damage = DamageSystem.calculate_damage(caster, target, base_damage, "fire")
actual_damage = target.take_damage(damage, "fire")
return {
"success": True,
"message": f"{caster.name} 施放火球术,对 {target.name} 造成 {actual_damage} 点火焰伤害!",
"damage": actual_damage,
"mana_cost": self.mana_cost
}
def can_execute(self, caster: GameCharacter) -> bool:
return super().can_execute(caster) and caster.mana >= self.mana_cost
class HealSkill(Skill):
"""治疗术技能的具体实现"""
def __init__(self):
super().__init__("治疗术", mana_cost=25, cooldown=2)
def execute(self, caster: GameCharacter, target: GameCharacter = None) -> Dict[str, any]:
"""执行治疗术"""
if not caster.is_alive():
return {"success": False, "message": "施法者已死亡"}
if not self.can_execute(caster):
return {"success": False, "message": "无法施放治疗术"}
# 如果没有指定目标,治疗自己
if not target:
target = caster
# 消耗魔法
caster.mana -= self.mana_cost
self.current_cooldown = self.cooldown
# 计算治疗量
heal_amount = 40
if hasattr(caster, 'wisdom'):
heal_amount += caster.wisdom * 3
healed = target.heal(heal_amount)
return {
"success": True,
"message": f"{caster.name} 施放治疗术,为 {target.name} 恢复了 {healed} 点生命值!",
"healing": healed,
"mana_cost": self.mana_cost
}
# 特殊8:装备实现
class SwordEquipment(Equipment):
"""剑类装备的具体实现"""
def __init__(self, name: str, rarity: str, level_requirement: int, attack_bonus: int):
super().__init__(name, rarity, level_requirement)
self.attack_bonus = attack_bonus
@property
def equipment_type(self) -> str:
return "weapon"
def get_stats(self) -> Dict[str, int]:
stats = {"attack": self.attack_bonus}
# 稀有度加成
if self.rarity == "rare":
stats["critical_chance"] = 5 # 5%暴击率
elif self.rarity == "epic":
stats["attack"] += 5
stats["critical_chance"] = 8
elif self.rarity == "legendary":
stats["attack"] += 10
stats["critical_chance"] = 12
stats["strength"] = 5 # 力量加成
return stats
def can_equip(self, character: GameCharacter) -> bool:
# 只有战士和弓箭手可以装备剑
return (super().can_equip(character) and
character.character_type in ["战士", "弓箭手"])
class RobeEquipment(Equipment):
"""长袍装备的具体实现"""
def __init__(self, name: str, rarity: str, level_requirement: int, defense_bonus: int,
mana_bonus: int):
super().__init__(name, rarity, level_requirement)
self.defense_bonus = defense_bonus
self.mana_bonus = mana_bonus
@property
def equipment_type(self) -> str:
return "armor"
def get_stats(self) -> Dict[str, int]:
stats = {
"defense": self.defense_bonus,
"max_mana": self.mana_bonus
}
if self.rarity == "rare":
stats["intelligence"] = 3
elif self.rarity == "epic":
stats["defense"] += 5
stats["max_mana"] += 20
stats["intelligence"] = 5
elif self.rarity == "legendary":
stats["defense"] += 10
stats["max_mana"] += 40
stats["intelligence"] = 8
stats["wisdom"] = 5
return stats
def can_equip(self, character: GameCharacter) -> bool:
# 法师和治疗者可以装备长袍
return (super().can_equip(character) and
character.character_type in ["法师", "治疗者"])
# 特殊9:角色工厂实现
class RPGCharacterFactory(CharacterFactory):
"""RPG角色工厂的具体实现"""
def create_character(self, character_type: str, name: str, **kwargs) -> GameCharacter:
character_type = character_type.lower()
if character_type == "warrior":
return Warrior(name, kwargs.get("level", 1))
elif character_type == "mage":
mage = Mage(name, kwargs.get("level", 1))
# 法师默认学会火球术
mage.learn_spell(FireballSkill())
return mage
elif character_type == "archer":
return Archer(name, kwargs.get("level", 1))
elif character_type == "healer":
healer = Healer(name, kwargs.get("level", 1))
# 治疗者默认学会治疗术
healer.learn_spell(HealSkill())
return healer
elif character_type == "monster":
monster_type = kwargs.get("monster_type", "goblin")
return Monster(name, monster_type, kwargs.get("level", 1))
else:
raise ValueError(f"不支持的角色类型: {character_type}")
def create_skill(self, skill_type: str, **kwargs) -> Skill:
skill_type = skill_type.lower()
if skill_type == "fireball":
return FireballSkill()
elif skill_type == "heal":
return HealSkill()
elif skill_type == "multi_shot":
return MultiShotSkill(kwargs.get("arrow_count", 3))
elif skill_type == "rage_attack":
return RageAttackSkill(kwargs.get("rage_cost", 50))
else:
raise ValueError(f"不支持的技能类型: {skill_type}")
def create_equipment(self, equipment_type: str, **kwargs) -> Equipment:
equipment_type = equipment_type.lower()
if equipment_type == "sword":
return SwordEquipment(
name=kwargs.get("name", "铁剑"),
rarity=kwargs.get("rarity", "common"),
level_requirement=kwargs.get("level_requirement", 1),
attack_bonus=kwargs.get("attack_bonus", 10)
)
elif equipment_type == "robe":
return RobeEquipment(
name=kwargs.get("name", "布袍"),
rarity=kwargs.get("rarity", "common"),
level_requirement=kwargs.get("level_requirement", 1),
defense_bonus=kwargs.get("defense_bonus", 5),
mana_bonus=kwargs.get("mana_bonus", 20)
)
elif equipment_type == "bow":
return BowEquipment(
name=kwargs.get("name", "木弓"),
rarity=kwargs.get("rarity", "common"),
level_requirement=kwargs.get("level_requirement", 1),
attack_bonus=kwargs.get("attack_bonus", 8),
dexterity_bonus=kwargs.get("dexterity_bonus", 2)
)
else:
raise ValueError(f"不支持的装备类型: {equipment_type}")
# 主程序:演示一般与特殊的应用
def demonstrate_general_special():
print("=== 游戏角色系统示例:一般与特殊的应用 ===\n")
# 1. 创建角色工厂
factory = RPGCharacterFactory()
# 2. 创建各种角色(特殊化实例)
print("创建游戏角色:")
warrior = factory.create_character("warrior", "亚瑟", level=5)
mage = factory.create_character("mage", "梅林", level=5)
archer = factory.create_character("archer", "罗宾", level=5)
healer = factory.create_character("healer", "艾拉", level=5)
monster = factory.create_character("monster", "哥布林首领", monster_type="goblin", level=5)
characters = [warrior, mage, archer, healer, monster]
for character in characters:
print(f" - {character.name}: {character.character_type} Lv.{character.level}")
# 3. 演示多态:通过一般接口调用特殊方法
print("\n多态演示(通过GameCharacter接口操作):")
for character in characters:
# 所有角色都有相同的接口
status = character.get_status()
print(f"{status['name']}: HP {status['health']}, MP {status['mana']}, 存活: {status['alive']}")
# 但具体行为不同
if isinstance(character, Warrior):
print(f" - 怒气值: {character.rage}/{character.max_rage}")
elif isinstance(character, Mage):
print(f" - 智力: {character.intelligence}")
elif isinstance(character, Archer):
print(f" - 箭矢: {character.arrows}/{character.max_arrows}")
elif isinstance(character, Healer):
print(f" - 信仰: {character.faith}/{character.max_faith}")
# 4. 演示战斗系统
print("\n战斗演示:")
# 创建一个敌人
dragon = factory.create_character("monster", "火龙", monster_type="dragon", level=8)
print(f"\n战斗开始: {warrior.name} vs {dragon.name}")
# 战斗回合
for round_num in range(1, 4):
print(f"\n第{round_num}回合:")
# 战士攻击
if warrior.is_alive() and dragon.is_alive():
damage, message = warrior.attack(dragon)
print(f" {message}")
# 龙攻击
if dragon.is_alive() and warrior.is_alive():
damage, message = dragon.attack(warrior)
print(f" {message}")
# 显示状态
print(f" {warrior.name}: {warrior.health}/{warrior.max_health} HP")
print(f" {dragon.name}: {dragon.health}/{dragon.max_health} HP")
# 5. 演示治疗系统
print("\n治疗演示:")
# 战士受伤
warrior.health = 20
print(f"{warrior.name} 受伤了: {warrior.health}/{warrior.max_health} HP")
# 治疗者治疗战士
if isinstance(healer, Healer):
heal_result = healer.heal_ally(warrior)
print(f" {heal_result['message']}")
print(f" 治疗后: {warrior.name} {warrior.health}/{warrior.max_health} HP")
# 6. 演示技能系统
print("\n技能演示:")
# 法师施放火球术
if isinstance(mage, Mage):
spell_result = mage.cast_spell("火球术", dragon)
print(f" {spell_result['message']}")
# 7. 演示装备系统
print("\n装备演示:")
# 创建装备
sword = factory.create_equipment("sword", name="王者之剑", rarity="epic",
level_requirement=5, attack_bonus=25)
if isinstance(warrior, Warrior):
if sword.can_equip(warrior):
print(f" {warrior.name} 可以装备 {sword.name}")
print(f" 装备属性: {sword.get_stats()}")
else:
print(f" {warrior.name} 不能装备 {sword.name}")
# 8. 演示升级系统
print("\n升级演示:")
# 给角色经验
for character in [warrior, mage]:
print(f"\n{character.name} 获得经验:")
old_level = character.level
# 获得足够升级的经验
exp_needed = character._experience_to_next_level()
character.addExperience(exp_needed)
if character.level > old_level:
print(f" {character.name} 升级到 {character.level} 级!")
# 显示新状态
status = character.get_status()
print(f" 当前状态: HP {status['health']}, MP {status['mana']}")
# 9. 演示一般接口的统一处理
print("\n一般接口的统一处理演示:")
# 创建角色列表(包含不同类型的角色)
party = [
factory.create_character("warrior", "战士A"),
factory.create_character("mage", "法师A"),
factory.create_character("archer", "弓箭手A"),
factory.create_character("healer", "治疗者A")
]
# 通过一般接口统一处理
print("队伍状态:")
for member in party:
status = member.get_status()
print(f" {status['name']} [{status['type']}] - HP: {status['health']}, 存活: {status['alive']}")
# 统一治疗所有成员
print("\n统一治疗队伍:")
for member in party:
if member.is_alive():
healed = member.heal(30)
if healed > 0:
print(f" {member.name} 恢复了 {healed} 点生命值")
# 10. 演示特殊方法
print("\n特殊方法演示:")
# 战士的怒气技能
if isinstance(warrior, Warrior):
warrior.rage = 80 # 设置怒气值
print(f"{warrior.name} 怒气值: {warrior.rage}/{warrior.max_rage}")
if dragon.is_alive():
damage, message = warrior.use_rage_skill(dragon)
print(f" {message}")
# 法师的冥想
if isinstance(mage, Mage):
mage.mana = 10 # 设置低魔法值
print(f"\n{mage.name} 魔法值: {mage.mana}/{mage.max_mana}")
meditate_result = mage.meditate()
print(f" {meditate_result['message']}")
print(f" 冥想后: {mage.mana}/{mage.max_mana} MP")
# 弓箭手的多重射击
if isinstance(archer, Archer):
archer.replenish_arrows(10) # 补充箭矢
# 创建多个目标
targets = [
factory.create_character("monster", "哥布林A", monster_type="goblin"),
factory.create_character("monster", "哥布林B", monster_type="goblin"),
factory.create_character("monster", "哥布林C", monster_type="goblin")
]
print(f"\n{archer.name} 使用多重射击:")
multi_result = archer.multi_shot(targets)
print(f" {multi_result['message']}")
for result in multi_result.get("results", []):
print(f" {result['message']}")
# 运行演示
if __name__ == "__main__":
demonstrate_general_special()
三、 一般与特殊的最佳实践
1. 继承层次设计
# 正确的继承层次设计
from abc import ABC, abstractmethod
# 不好的设计:过深的继承层次
class GameObject:
pass
class Character(GameObject):
pass
class Player(Character):
pass
class Warrior(Player):
pass
class Tank(Warrior):
pass # 层次过深,难以维护
# 好的设计:使用组合和接口
class GameObject(ABC):
@abstractmethod
def update(self): pass
class PositionComponent:
def __init__(self):
self.x = 0
self.y = 0
class HealthComponent:
def __init__(self, max_health):
self.max_health = max_health
self.current_health = max_health
class Character(GameObject):
def __init__(self):
self.position = PositionComponent()
self.health = HealthComponent(100)
self.components = {}
def add_component(self, name, component):
self.components[name] = component
def get_component(self, name):
return self.components.get(name)
# 角色通过组合获得能力
class Warrior:
def __init__(self):
self.character = Character()
self.character.add_component("combat", CombatComponent())
self.character.add_component("equipment", EquipmentComponent())
# 更好的设计:使用角色模板
class CharacterTemplate:
def __init__(self, character_type, base_stats, abilities):
self.character_type = character_type
self.base_stats = base_stats
self.abilities = abilities
class CharacterFactory:
_templates = {
"warrior": CharacterTemplate(
"warrior",
{"health": 100, "attack": 15, "defense": 10},
["slash", "block"]
),
"mage": CharacterTemplate(
"mage",
{"health": 60, "attack": 20, "defense": 5, "mana": 100},
["fireball", "teleport"]
)
}
def create_character(self, character_type, name):
template = self._templates[character_type]
character = Character(name)
# 应用模板
for stat, value in template.base_stats.items():
setattr(character, stat, value)
# 添加能力
for ability in template.abilities:
character.learn_ability(ability)
return character
2. 避免继承误用
# 常见继承误用及解决方案
# 误用1:使用继承实现代码复用,但不符合is-a关系
class Logger:
def log(self, message):
print(f"LOG: {message}")
class Database(Logger): # 错误:Database is not a Logger
def query(self, sql):
self.log(f"Executing: {sql}") # 只是想要复用log方法
# 执行查询...
# 正确:使用组合
class Database:
def __init__(self, logger=None):
self.logger = logger or Logger()
def query(self, sql):
self.logger.log(f"Executing: {sql}")
# 执行查询...
# 误用2:为添加功能而继承
class User:
def __init__(self, username):
self.username = username
class Admin(User): # Admin is a User,这看起来合理
def delete_user(self, user):
# 管理员特有功能
pass
# 但如果有多种角色呢?
class Moderator(User):
def edit_post(self, post):
pass
class VIP(User):
def access_vip_content(self):
pass
# 如果用户可以有多个角色怎么办?
# 正确:使用角色组件
class User:
def __init__(self, username):
self.username = username
self.roles = set()
def add_role(self, role):
self.roles.add(role)
def has_role(self, role):
return role in self.roles
class Role:
def __init__(self, name, permissions):
self.name = name
self.permissions = permissions
# 创建角色
admin_role = Role("admin", ["delete_user", "edit_user"])
moderator_role = Role("moderator", ["edit_post", "delete_post"])
# 用户可以拥有多个角色
user = User("john")
user.add_role(admin_role)
user.add_role(moderator_role)
# 误用3:过度使用继承导致脆弱基类问题
class DataProcessor:
def process(self, data):
# 处理数据...
result = self._transform(data) # 调用钩子方法
return self._finalize(result) # 调用另一个钩子方法
def _transform(self, data):
return data.upper() # 默认实现
def _finalize(self, result):
return result.strip()
class SpecialProcessor(DataProcessor):
def _transform(self, data):
# 覆盖父类方法
return data.lower()
# 注意:如果父类修改了_process方法,可能会破坏子类
# 正确:使用策略模式
class TransformationStrategy(ABC):
@abstractmethod
def transform(self, data): pass
class UppercaseStrategy(TransformationStrategy):
def transform(self, data):
return data.upper()
class LowercaseStrategy(TransformationStrategy):
def transform(self, data):
return data.lower()
class DataProcessor:
def __init__(self, transformation_strategy):
self.transformation_strategy = transformation_strategy
def process(self, data):
result = self.transformation_strategy.transform(data)
return result.strip()
四、 一般与特殊的优势对比
| 方面 | 一般化的优势 | 特殊化的优势 |
|---|---|---|
| 代码复用 | 高:通用代码在基类中实现,所有子类复用 | 低:特定代码无法复用 |
| 维护性 | 高:修改基类影响所有子类,但需谨慎 | 低:修改只影响特定类 |
| 扩展性 | 高:通过继承容易添加新功能 | 中:需要创建新类 |
| 灵活性 | 中:受限于继承关系 | 高:可以自由实现特定行为 |
| 类型安全 | 高:编译时类型检查 | 低:运行时可能出错 |
| 设计复杂度 | 高:需要良好设计继承层次 | 低:简单直接的实现 |
| 多态支持 | 高:天然支持多态 | 低:需要显式类型检查 |
| 测试难度 | 中:需要测试基类和子类 | 低:只需测试具体类 |
五、 实际应用建议
-
遵循Liskov替换原则:
- 子类必须能够替换父类而不影响程序正确性
- 子类不应该加强前置条件或减弱后置条件
-
优先使用组合:
- "组合优于继承"是重要的设计原则
- 使用组合可以获得更大的灵活性
- 只有在真正的is-a关系时才使用继承
-
适度使用继承:
- 避免超过3层的继承深度
- 使用抽象基类定义接口
- 使用混入(Mixin)添加横切关注点
-
使用模板方法模式:
- 在基类中定义算法骨架
- 让子类重写特定步骤
- 保持算法的整体结构不变
-
利用多态:
- 通过基类接口操作对象
- 减少条件判断,提高代码可维护性
- 使用策略模式替代继承
-
考虑使用组件系统:
- 对于复杂系统,使用组件组合替代继承
- 每个组件负责单一功能
- 实体通过组合组件获得能力
-
文档化继承关系:
- 明确记录每个类的职责
- 说明继承关系的合理性
- 记录子类对父类行为的修改
-
测试继承层次:
- 测试基类的通用行为
- 测试每个子类的特殊行为
- 确保子类遵守父类的契约
一般与特殊是软件设计的核心思维模式。良好的继承设计能够显著提高代码的复用性和可维护性,但不当的继承会导致代码脆弱和难以维护。掌握在一般化和特殊化之间找到平衡的能力,是成为优秀软件设计师的关键。记住:面向接口编程,而非实现编程,这样可以保持系统的灵活性和可扩展性。
948

被折叠的 条评论
为什么被折叠?



