某游戏公司现欲开发一款面向儿童的模拟游戏,该游戏主要模拟现实世界中各种鸭子的发声特征、飞行特征和外观特征。游戏需要模拟的鸭子种类及其特征。当前设计为有四类鸭子RubberDuck、MallardDuck、CottonDuck和RedHeadDuck。每类鸭子都为支持将来能够模拟更多种类鸭子的特征,采用策略模式实现模拟python
时间: 2023-12-03 11:45:04 浏览: 170
首先,我们需要定义一个鸭子基类Duck,其中包含鸭子的属性和方法,如下:
```python
class Duck:
def __init__(self):
self.fly_behavior = None
self.quack_behavior = None
self.appearance = ""
def set_fly_behavior(self, fb):
self.fly_behavior = fb
def set_quack_behavior(self, qb):
self.quack_behavior = qb
def fly(self):
self.fly_behavior.fly()
def quack(self):
self.quack_behavior.quack()
def display(self):
print("I am a " + self.appearance + " duck.")
```
接下来,我们定义鸭子的飞行和叫声行为,作为策略模式的具体实现:
```python
class FlyWithWings:
def fly(self):
print("I can fly with wings!")
class FlyNoWay:
def fly(self):
print("I can't fly!")
class Quack:
def quack(self):
print("Quack! Quack!")
class Squeak:
def quack(self):
print("Squeak! Squeak!")
```
然后,我们定义具体的鸭子类:
```python
class RubberDuck(Duck):
def __init__(self):
super().__init__()
self.set_fly_behavior(FlyNoWay())
self.set_quack_behavior(Squeak())
self.appearance = "rubber"
class MallardDuck(Duck):
def __init__(self):
super().__init__()
self.set_fly_behavior(FlyWithWings())
self.set_quack_behavior(Quack())
self.appearance = "mallard"
class CottonDuck(Duck):
def __init__(self):
super().__init__()
self.set_fly_behavior(FlyNoWay())
self.set_quack_behavior(Squeak())
self.appearance = "cotton"
class RedHeadDuck(Duck):
def __init__(self):
super().__init__()
self.set_fly_behavior(FlyWithWings())
self.set_quack_behavior(Quack())
self.appearance = "red head"
```
最后,我们可以使用这些类来模拟鸭子的飞行、叫声和外观:
```python
if __name__ == '__main__':
rubber_duck = RubberDuck()
rubber_duck.display()
rubber_duck.quack()
rubber_duck.fly()
mallard_duck = MallardDuck()
mallard_duck.display()
mallard_duck.quack()
mallard_duck.fly()
cotton_duck = CottonDuck()
cotton_duck.display()
cotton_duck.quack()
cotton_duck.fly()
red_head_duck = RedHeadDuck()
red_head_duck.display()
red_head_duck.quack()
red_head_duck.fly()
```
输出结果:
```
I am a rubber duck.
Squeak! Squeak!
I can't fly!
I am a mallard duck.
Quack! Quack!
I can fly with wings!
I am a cotton duck.
Squeak! Squeak!
I can't fly!
I am a red head duck.
Quack! Quack!
I can fly with wings!
```
阅读全文