策略模式

87 阅读1分钟

适用场景

对同一问题,提供不同的解决方案。就好比两国打战,目的只有一个就是获取更多的资源,但是策略有很多,一种是直接真刀真枪,另外一种是互惠双赢。

UML

classDiagram
class Abstraction{
+some_action()
}

class Implementation1{
+some_action()
}

class Implementation2{
+some_action()
}

User -- Abstraction

Abstraction <|.. Implementation1
Abstraction <|.. Implementation2

用户只需要同一个接口打交道,不同的策略都实现了该接口。
在python中,因为只需要实现同一接口,函数又是对象,所以不要单独的类,直接用函数实现即可。

class Target:
    def __init__(self,im):
        self.im = im
        
    def run(self):
        self.im.some_action()
        
class Implementation1:
    def some_action():
        do_someing
        
class Implementaion2:
    def some_action():
        do_someing
        
def main():
    if condition_A:
        im = Implementation1()
    elif condition_B:
        im = Implementaion2()
    .....
    target = Target(im)
    target.run()

可以看到,所有的模式都是尽量降低代码间的耦合,提高可读性,可维护性和可扩展性。