python设计模式:策略模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import abc

# 策略父类
class Strategy(metaclass=abc.ABCMeta):
@abc.abstractmethod
def execute(self):
pass

# 策略类:攻击
class Attack(Strategy):
def __init__(self, level):
self.level = level

def execute(self):
print(f"执行 {self.level} 级别的进攻")

# 策略类:防守
class Defend(Strategy):
def __init__(self, level):
self.level = level

def execute(self):
print(f"执行 {self.level} 级别的防守")

# 策略类:撤退
class Retreat(Strategy):
def __init__(self, distance):
self.distance = distance

def execute(self):
print(f"撤退 {self.distance} 公里")

# 策略类:投降
class Surrender(Strategy):
@classmethod
def execute(cls):
print("投降")

# 使用者类:军队
class Army:
strategy = None

@classmethod
def set_strategy(cls, strategy):
cls.strategy = strategy

@classmethod
def execute(cls):
if cls.strategy:
cls.strategy.execute()
else:
print("暂无策略")


Army.execute()

Army.set_strategy(Attack(10))
Army.execute()

Army.set_strategy(Defend(5))
Army.execute()

Army.set_strategy(Retreat(30))
Army.execute()

Army.set_strategy(Surrender)
Army.execute()