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

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

    原文作者:ruguowoshiyu
    原文地址: https://blog.csdn.net/ruguowoshiyu/article/details/80806046
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞