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


發佈了54 篇原創文章 · 獲贊 11 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章