我如何在python中实现这个解决方案(策略设计模式)?我这里有一些粗略的代码



我正在尝试使用策略设计模式在python中实现此解决方案。我是OOP的新手,目前正在和我的教授一起研究这个问题。

基本上,问题是要有一个抽象类(或者更确切地说是一个接口)和两个具体的子类(汽车和公共汽车),它们具有返回运输成本的方法"find()"。在他们返回各自的成本后,抽象父类将选择更便宜的交通工具,并输出一个打印声明"我选择公共汽车"。

这是粗略的代码。感谢能帮助我的人!我相信我的代码在某个地方是错误的。

from abc import ABCMeta, abstractmethod
class transporter(metaclass=ABCMeta):
    'abstract parent class'
        @abstractmethod
        def find(self, cost):
            pass
    class car(transporter):
        def find(self):
            return "Cost of car travel is 50"
        def cost(self):
            return C = 50

    class bus(transporter):
        def find(self):
            return"Cost of bus travel is 20"
        def cost(self):
            return B = 20

    if __name__ == "__main__" :

        find_car = car()
        find_bus = bus()
        find_car.cost().execute()
        find_bus.cost().execute()

我不是设计模式专家,但我认为这更接近你想要的:

from abc import ABCMeta, abstractmethod
from operator import methodcaller
class Transportation(object):
    def __init__(self):
        # instantiate concrete transporter with lowest cost
        self.transporter = min((Car, Bus), key=methodcaller('cost'))()
    def go_for_ride(self):
        self.transporter.travel()
class Transporter(metaclass=ABCMeta):
    @abstractmethod
    def cost(self):
        pass
    @abstractmethod
    def travel(self):
        pass
class Car(Transporter):
    @classmethod
    def cost(cls):
        return 50
    def travel(self):
        print('riding in a car')
class Bus(Transporter):
    @classmethod
    def cost(cls):
        return 20
    def travel(self):
        print('riding in a bus')
if __name__ == "__main__" :
    transportation = Transportation()
    transportation.go_for_ride()  # -> riding in a bus

相关内容

最新更新