工厂模式与泛型

时间:2016-02-05 10:54:26

标签: java groovy factory-pattern

我正在尝试用泛型实现工厂模式。我不确定我是否正确实施

interface DocumentValidator<T> {
    Boolean validate(Document document, T object)

}

class ShipmentDocumentValidator implements DocumentValidator<Shipment>{
      @Override
       Boolean validate(Document document, Shipment object) {
           return true
       }
}

class DocumentValidatorFactory {
    static DocumentValidator forClass(Class clazz) {
        if (clazz.simpleName.contains('Shipment')) {
            return new ShipmentDocumentValidator ();
        }
    }
 }

致电代码:

 DocumentValidator validator = DocumentValidatorFactory.forClass(Shipment.class)

我不认为我应该依赖于班级名称,但我怎么能实现

3 个答案:

答案 0 :(得分:1)

您的工厂可以通过groovy的多种调度方法解析简化。例如:

class DocumentValidatorFactory {
    DocumentValidator forClass(Shipment shipment) {
        new ShipmentDocumentValidator()
    }
    DocumentValidator forClass(Invoice invoice) {
        new InvoiceDocumentValidator()
    }
}

Groovy非常聪明,可以通过在运行时查看参数类来调用正确的方法。

答案 1 :(得分:1)

Ditto WillP和Ataylor。让我补充一点,另一种选择是将验证器的创建放入要验证的类中。例如:

public interface Validation
{
  public Validator getValidator();
}
public class Shipment implements Validation
{
  ... whatever ...
  public Validator getValidator()
  {
    return new ShipmentValidator();
  }
}
public class Restock implements Validation
{
  ... whatever ...
  public Validator getValidator()
  {
    return new RestockValidator();
  }
}
public class ValidationFactory
{
  public getValidator(Validation x)
  {
    return x.getValidator();
  }
}

答案 2 :(得分:0)

如果你的参数是a String,那么这种比较是可行的,但在这种情况下,你可以简单地比较一下这个类:

if (clazz == Shipment) {
    return new ShipmentDocumentValidator ();
}

但是你也可以使用一个以类作为键的映射,并使用验证器作为值:

class Shipment {}
class Invoice {}
class Document {}

interface DocumentValidator<T> {
    Boolean validate(Document document, T object)
}

class ShipmentDocumentValidator implements DocumentValidator<Shipment>{
   Boolean validate(Document document, Shipment object) {
       true
   }
}

class InvoiceDocumentValidator implements DocumentValidator<Invoice>{
   Boolean validate(Document document, Invoice object) {
       true
   }
}

class DocumentValidatorFactory {
    static DocumentValidator forClass(Class clazz) {
        [
            (Shipment) : ShipmentDocumentValidator,
            (Invoice)  : InvoiceDocumentValidator
        ][clazz].newInstance()
    }
 }


assert DocumentValidatorFactory.forClass(Shipment) instanceof ShipmentDocumentValidator
assert DocumentValidatorFactory.forClass(Invoice) instanceof InvoiceDocumentValidator