简体   繁体   English

Generics 和工厂方法

[英]Generics and factory method

I have two simple classes that extends an interface:我有两个扩展接口的简单类:

public interface Product 
{

}

public class ProductA implements Product
{

}

public class ProductB implements Product
{

}

I have two 'services' classes: ServiceA and ServiceB.我有两个“服务”类:ServiceA 和 ServiceB。 Each one works with one of the Product classes defined before.每个都与之前定义的产品类之一一起使用。 Both implements Service interface.两者都实现了服务接口。

public interface Service<T extends Product>
{
   public void print (T product); 
}

public class ServiceA implements Service<ProductA>
{
  public void print (ProductA product)
  {
      System.out.println("Product A");
  } 
}


public class ServiceB implements Service<ProductB>
{
  public void print (ProductB product)
  {
      System.out.println("Product B");
  }

}

I would like to developed a factory to instantiate my services:我想开发一个工厂来实例化我的服务:

[BEFORE I FOUND SOLUTION] [在我找到解决方案之前]

public class FactoryService
{
   public static Service<? extends Product> getService (String serviceType)
   {
      Service<? extends Product> s = null;
    
      if ("1".equals(serviceType))              
          s =  new ServiceA();
      else if ("2".equals(serviceType))     
          s = new ServiceB();           
    
      return s;
  }
}

[SOLUTION] [解决方案]

public static <T> T getService (Type targetType)
{
    T service = null;
    
    if (!targetType.getClass().isInstance(Product.class))
        throw new RuntimeException();
        
    if (ProductA.class.getTypeName().equals(targetType.getTypeName()))
        service = (T) new ServiceA();
    else if (ProductB.class.getTypeName().equals(targetType.getTypeName()))
        service = (T) new ServiceB();
    
    return service;     
}

When I tried to use my factory I get compile errors:当我尝试使用我的工厂时,出现编译错误:

[BEFORE I FOUND SOLUTION] [在我找到解决方案之前]

public static void main(String[] args)
{       
    Product pA = new ProductA();
    Product pB = new ProductB();
    Service<? extends Product> service = FactoryService.getService("1");
    service.print(pA);                      
}

[SOLUTION] [解决方案]

public static void main(String[] args)
{       
    Product pA = new ProductA();
    Product pB = new ProductB();

    Service<Product> service = FactoryService.getService(pA.getClass());
    service.print(pA);
    
    service = FactoryService.getService(pB.getClass());
    service.print(pB);
    
// No compilation errors
    
}

The error says:错误说:

The method print(capture#5-of? extends Product) in the type Service<capture#5-of? Service<capture#5-of? 类型中的方法 print(capture#5-of? extends Product) extends Product> is not applicable for the arguments (Product). extends Product> 不适用于 arguments(产品)。

How can I solve this problem?我怎么解决这个问题?

Thanks谢谢

When you want to use generics in declaring a type, you shouldn't use <? extends Type>当你想使用 generics 来声明一个类型时,你不应该使用<? extends Type> <? extends Type> as Jesper pointed out. <? extends Type>正如 Jesper 指出的那样。 Instead you should use <Type> .相反,您应该使用<Type> In your case, replace Service<? extends Product>在您的情况下,更换Service<? extends Product> Service<? extends Product> with Service<Product> .Service<Product> Service<? extends Product> > 。
Now you'll get another error:现在你会得到另一个错误:

Type mismatch: cannot convert from ServiceA to Service<Product>类型不匹配:无法从 ServiceA 转换为 Service<Product>

The solution I suggest is instead of defining ServiceA and ServiceB , to just use the Service#print method and check the generic type, then do what is necessary.我建议的解决方案不是定义ServiceAServiceB ,而是使用Service#print方法并检查泛型类型,然后执行必要的操作。 The FactoryService#getService method is not needed in this case.在这种情况下,不需要FactoryService#getService方法。

Spoiler for my solution (try without it first):我的解决方案的剧透(先尝试不使用它):

public class Service<T extends Product> {
public void print(T product) {
if (product instanceof ProductA) {
System.out.println("Product A");
} else if (product instanceof ProductB) {
System.out.println("Product B");
}
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM