Java多态机制在实际中的应用
PaymentTypeService.java
/**
* 支付方式接口
* @date: 2018年4月23日 下午2:20:09
*/
public interface PaymentTypeService {
public String type();
public void methodA();
public void methodB();
}
APaymentTypeServiceImpl.java
import org.springframework.stereotype.Service;
/**
* 支付方式A实现类
* @date: 2018年4月23日 下午2:20:27
*/
@Service
public class APaymentTypeServiceImpl implements PaymentTypeService {
private final String type = "A";
@Override
public void methodA() {
// TODO Auto-generated method stub
System.out.println("PaymentType A invoke methodA");
}
@Override
public void methodB() {
// TODO Auto-generated method stub
System.out.println("PaymentType A invoke methodB");
}
@Override
public String type() {
return type;
}
}
BPaymentTypeServiceImpl.java
/**
* 支付方式B实现类
* @date: 2018年4月23日 下午2:20:27
*/
@Service
public class BPaymentTypeServiceImpl implements PaymentTypeService {
private final String type = "B";
@Override
public void methodA() {
// TODO Auto-generated method stub
System.out.println("PaymentType B invoke methodA");
}
@Override
public void methodB() {
// TODO Auto-generated method stub
System.out.println("PaymentType B invoke methodB");
}
@Override
public String type() {
return type;
}
}
DemoController.java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
private Map<String, PaymentTypeService> paymentTypeServices;
/**
* 构造函数初始化不同支付方式类型和实现类引用map
* @param services
*/
public DemoController(@Autowired List<PaymentTypeService> services){
paymentTypeServices = services.stream().collect(Collectors.toMap(PaymentTypeService::type, i->i));
}
/**
* 请求某个支付方式
* @date: 2018年4月23日 下午2:21:28
* @param type
*/
@GetMapping("/test/{type}")
public void test(@PathVariable("type") String type){
// 获取该支付方式实现类
PaymentTypeService service = paymentTypeServices.get(type);
service.methodA();
service.methodB();
}
}
