我需要问一下对象类,但这是一个不好的做法.这种情况的替代方案?

gal*_*007 7 uml design-patterns double-dispatch visitor-pattern

我在扩展应用程序时遇到了麻烦.这是一个考勤记录系统.目前,每位员工都通过具有QR码的卡记录出勤率.现在他们想要添加指纹识别,直到他们要求两种形式的识别必须在系统中共存时才会出现问题.因此,系统必须能够感知员工的QR,以及他的指纹.

我有以下课程:

通过.equalsTo(id)方法在QrIdStrategy中修复它的方法是:

equalsTo(id){
  if (id == isKindOf (QrIdStrategy))
    if (this.getEmployeeId () == id.getEmployeeId ())
      return true;

  return false;
}
Run Code Online (Sandbox Code Playgroud)

但我明白,询问一个对象的类是一个不好的做法,并不想这样做.我该如何解决?

我想到了访问者模式,但我仍然有同样的问题来比较两个不同类型的类(因为系统可以扫描这两种类型中的任何一种)

在此输入图像描述

lis*_*isp 1

关于你的第一灵魂

问题是 QrId 和 FingerprintId 确实没有任何共同点。IdentityStrategy 显示您想要比较它们,但您不能。解决方案可能是添加类似于getUniversalID() : stringIdentificationStrategy 的内容并在派生类中实现它们。那么你可以:

matchWithLocation(IdentificationStrategy identificationStrategy)
{
    return this.identificationStrategy.getUniversalId()
        == identificationStrategy.getUniversalID();
}
Run Code Online (Sandbox Code Playgroud)

但是,您可能会发现 getUniversalId(确保不同类型的 ID 不会冲突)的实现存在问题。

关于你的第二个解决方案

在这种情况下,对 Visitor 的一个很好的调整是向 Employee 添加方法getQr() : QrIdStrategygetFingerprint() : FingerprintStrategy(因为员工使用两种识别方法,正如您提到的),更改equalsTo(id: IdentificationStrategy)check(employee: Employee). 那么QrStrategy.check将是:

    return this.getEmployeeId() == employee.getQr().getEmployeeId()
Run Code Online (Sandbox Code Playgroud)

并且FingerprintStrategy.check将是:

    return this.getMatchingViaFramework() == employee.getFingerprint().getMatchingViaFramework()
Run Code Online (Sandbox Code Playgroud)