python 设计模式(五) 策略模式(Strategy pattern)

本文介绍了Python中的策略模式,通过一个实例展示了如何使用该模式来避免大量if else语句,提高代码可维护性。当需要根据不同的条件执行不同操作时,策略模式提供了一种优雅的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一种常见的情况,根据参数的值来做相应处理。比如,同一个网页,对于管理员来说,某地方显示为编辑按钮,但对于一般用户则不显示。这个逻辑很容易实现,只需用if else实现即可。

一种场景,大学开学第一天。cs(computer science)专业的学生和es(software engineering)专业的同学共享辅导员。辅导员需要把这两个专业的学生都介绍一遍。如下,代码中实现了一个抽象student类。A_cs, B_se都继承自Student。还实现了一个Instructor类(辅导员类)。Instructor实现了introduce方法。此方法作用是对student对象进行介绍。根据不同专业的student,进行介绍。先看使用if else的实现,代码如下

import abc

class Student(object):

    __metaclass__ = abc.ABCMeta

    def __init__(self, *args, **kwargs):
        self.name = args[0]
        self.hobby = args[1]
        self.hometown = args[2]


class A_cs(Student):

    def __init__(self, *args, **kwargs):
        super(A_cs, self).__init__(*args, **kwargs) # 复用父类方法。super(类名,self).方法名


class B_se(Student):
    def __init__(self, *args, **kwargs):
        super(B_se, self).__init__(*args, **kwargs)


class Instructor(object):
    def __init__(self):
        pass

    def introduce(self, student):
        if isinstance(student, A_cs):
            print("student's name is %s, hobby is %s, come from %s, major is cs"
                  % (student.name, student.hobby, student.hometown))
        if isinstance(student, B_se):
            print("student's name is %s, hobby is %s, come from %s, major is es"
                  % (student.name, student.hobby, student.hometown))


if __name__ == '__main__':
    xiaoming = A_cs('xiaoming', 'pretty girl', 'zhengzhou')
    xiaogang = B_se('xiaogang', 'money and pretty girl', 'suzhou')
    instructor = Instructor()
    instructor.introduce(xiaoming)
    instructor.introduce(xiaogang)

结果

student's name is xiaoming, hobby is pretty girl, come from zhengzhou, major is cs
student's name is xiaogang, hobby is money and pretty girl, come from suzhou, major is es

从结果看,基本功能是实现了,但后期维护比较困难,如果新增加了一个im(information management) 专业的学生,那么势必修改Instructor中introduce中的代码。并且instructor辅导员只有一种介绍方法。确实听起来让人不爽啊。那么策略模式来了

如下

策略模式

把管理员需要做的介绍功能,添加到学生对象上去,让学生自己介绍自己。去掉了if else。如下代码

import abc

class Student(object):

    __metaclass__ = abc.ABCMeta

    def __init__(self, *args, **kwargs):
        self.name = args[0]
        self.hobby = args[1]
        self.hometown = args[2]

    @abc.abstractmethod
    def introduce(self):
        pass


class A_cs(Student):

    def __init__(self, *args, **kwargs):
        super(A_cs, self).__init__(*args, **kwargs) # 复用父类方法。super(类名,self).方法名

    def introduce(self):
        print("I am %s, I like %s, and i like money very much. in the future, "
              "we can make money together, by the way, I come from %s" % (self.name, self.hobby, self.hometown))


class B_se(Student):
    def __init__(self, *args, **kwargs):
        super(B_se, self).__init__(*args, **kwargs)

    def introduce(self):
        print("I am %s, I like %s and so on,I'm from %s,  it is a beautiful place"
              % (self.name, self.hobby, self.hometown))


class Instructor(object):
    def __init__(self):
        pass

    def introduce(self, student):
        return student.introduce()


if __name__ == '__main__':
    xiaoming = A_cs('xiaoming', 'pretty girl', 'zhengzhou')
    xiaogang = B_se('xiaogang', 'money and pretty girl', 'suzhou')
    instructor = Instructor()
    instructor.introduce(xiaoming)
    instructor.introduce(xiaogang)

结果

I am xiaoming, I like pretty girl, and i like money very much. in the future, we can make money together, by the way, I come from zhengzhou
I am xiaogang, I like money and pretty girl and so on,I'm from suzhou,  it is a beautiful place


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值