码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之策略模式

时间:2020-06-07 23:03:55      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:nbsp   排序   metaclass   上下文环境   ini   abc   sort   __init__   abs   

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()

 

设计模式之策略模式

标签:nbsp   排序   metaclass   上下文环境   ini   abc   sort   __init__   abs   

原文地址:https://www.cnblogs.com/loveprogramme/p/13062769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!