设计模式之策略模式
Posted loveprogramme
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之策略模式相关的知识,希望对你有一定的参考价值。
from abc import ABCMeta, abstractmethod from operator import itemgetter, attrgetter # 策略模式:三个角色:上下文环境、策略的抽象、具体的策略 # 简而言之:定义一系列算法,将每个算法都封装起来,并且使他们之间可以相互替换。 class Person: def __init__(self, name, age, weight, height): self.name = name self.age = age self.weight = weight self.height = height def showMyself(self): print("%s 年龄:%d 岁,体重: %0.2fkg,身高:%0.2fm" %(self.name, self.age, self.weight, self.height)) class ICompare(metaclass=ABCMeta): """比较算法""" @abstractmethod def comparable(self, person1, person2): pass class CompareByAge(ICompare): """通过年龄排序""" def comparable(self, person1, person2): return person1.age - person2.age class CompareByHeight(ICompare): """通过身高排序""" def comparable(self, person1, person2): return person1.height - person2.height class CompareByWeight(ICompare): """通过体重排序""" def comparable(self, person1, person2): return person1.weight - person2.weight class SortPerson: """Person的排序类""" def __init__(self, compare): self.__compare = compare def sort(self, personList): """ 排序算法 采用最简单的冒泡排序 """ n = len(personList) for i in range(0, n - 1): for j in range(0, n - 1 -i): if (self.__compare.comparable(personList[j], personList[j+1])) > 0: tmp = personList[j] personList[j] = personList[j+1] personList[j+1] = tmp if __name__ == "__main__": personList = [ Person("Tony", 2, 54.5, 0.82), Person("Jack", 3, 52.5, 0.86), Person("Eric", 5, 45.5, 0.72), Person("Helen", 1, 58.5, 0.84), ] # sortedPersons = sorted(personList, key=attrgetter("age")) ageSorter = SortPerson(CompareByAge()) ageSorter.sort(personList) print("根据年龄排序后的结果:") for person in personList: person.showMyself()
以上是关于设计模式之策略模式的主要内容,如果未能解决你的问题,请参考以下文章