根据条件执行略有不同的动作的Generalize方法

问题描述 投票:0回答:1

我有一个简化的类Animal,可以执行food_routine,其中的动作根据动物的类型而有所不同:

DOG = 'dog'
CAT = 'cat'

class Animal(object):
    def __init__(self, animal_type):
        if animal_type not in [CAT, DOG]:
            raise Exception('unexpected animal')
        self.animal_type = animal_type

def food_routine(self):
    self.come_to_plate()  # common code
    self.sniff_food()  # common code

    if self.animal_type == CAT:
        self.go_around_plate()

    self.eat_the_food()  # common code

    if self.animal_type == DOG:  # condition I want to avoid
        self.thank_owner()

    self.go_away_from_plate()  # common code

    # cats and dogs do different things after eating:
    if self.animal_type == CAT:  # condition I want to avoid
        self.go_lie_on_couch()
    elif self.animal_type == DOG:  # condition I want to avoid
        self.ask_for_walk_outside()

    self.sleep()  # common code

def sleep(self):
    print 'sleep'  # common code

def ask_for_walk_outside(self):
    print 'ask for a walk outside'

def go_lie_on_couch(self):
    print 'go lie on couch'

def go_away_from_plate(self):
    print 'go away from plate'  # common code

def thank_owner(self):
    print 'thank owner'  # only dogs thank owner

def eat_the_food(self):
    print 'eat the food'  # common code

def go_around_plate(self):
    print 'go around plate'

def sniff_food(self):
    print 'sniff food'  # common code

def come_to_plate(self):
    print 'come to plate'  # common code

我的问题是if语句使代码不可读。我试图通过创建两个类来解决它:一个用于Dog,一个用于Cat。每个动物只在food_routine中做他知道要做的事情(并从Animal中删除了该方法):

class Cat(Animal):
    def food_routine(self):
        self.come_to_plate()  # common code
        self.sniff_food()  # common code
        self.go_around_plate()
        self.eat_the_food()  # common code
        self.go_away_from_plate()  # common code
        self.go_lie_on_couch()
        self.sleep()  # common code


class Dog(Animal):
    def food_routine(self):
        self.come_to_plate()  # common code
        self.sniff_food()  # common code
        self.eat_the_food()  # common code
        self.thank_owner()
        self.go_away_from_plate()  # common code
        self.ask_for_walk_outside()
        self.sleep()  # common code

这会导致代码重复(common code行),我想避免。

所以我的问题是:什么是避免代码重复但又避​​免if语句以使代码可读且简单的良好实践?

python oop polymorphism
1个回答
1
投票

怎么样:

© www.soinside.com 2019 - 2024. All rights reserved.