如何为两个完全相同但实体不同的类推广逻辑?

2024-05-13 01:22:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的项目中有两个类:第一个是用comments做一些事情,第二个是用alertsAlertFilterServiceCommentFilterService

它们具有几乎相同的构造函数和完全相同的方法签名,如do_somethig_for_alerts(self)do_something_for_comments(self)。你知道吗

class AlertFilterService:
  do_somethig_for_alerts(self):
    some_code
    if
       code
    else:
       message['status'] = AlertStatus.NEW.value
       await self.db.store_alert(message)

class CommentFilterService
  do_somethig_for_comments(self):
    some_code
    if
       code
    else:
       message['status'] = CommentStatus.NEW.value
       await self.db.store_comment(message)

如何避免代码重复?我想要一个像FilterService这样的抽象类(包含所有公共部分)和两个具体的实现。最好的方法是什么?你知道吗


Tags: 方法selfmessagenewforifstatuscode
3条回答

如果您有两个几乎相同的类,而另一个类有一个很小的差异,那么您可以通过扩展它来对另一个类进行子类化。你知道吗

如果您想拥有一个类,请实现两个不同的方法来处理不同的情况,或者只创建一个方法来接受一个参数,该参数将根据传递的参数来处理情况

你可以试试那样的

def select_val_type(tag)            
            if (tag== "comments"
                    val== Comments.NEW.value
            else:
                    val == AlertStatus.NEW.value
            message['status'] = val
            if(tag == "comments")
                    await self.db.store_comments(message)
            else:
                    await self.db.store_alert(message)

你可以用很多方法来回答这个问题,所以在没有太多上下文的情况下,我将坚持一个非常笼统的答案。你知道吗

这是state pattern的一个非常通用/粗略的实现/用例。有关实现,请参见this link。你知道吗

class MessageStatus(object):
    def __init__(self, status_instance):
        self._status_instance = status_instance # maintain a ptr to the class containing your attributes

    def __call__(self):
        # some code
        if some_condition:
           # more code
        else:
            message['status'] = self.cls.NEW.value
            await self.status_instance.db.store_comment(message) 

The state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern's superclass.

注意:根据前面的状态模式概要,如果您想使其与状态模式保持一致,我建议您重构代码,以便注释/警报状态类是泛型状态类的子类,泛型状态类将包含上面的逻辑。你知道吗

相关问题 更多 >