Java多型機制在實際中的應用
阿新 • • 發佈:2019-02-12
在實際開發工作中,常常遇到一個功能有多種實現方式,比如支付方式,有分微信支付、京東支付、支付寶、銀聯等支付方式,不同支付方式的大概流程大抵相似,實現細節有所區別。這個時候就可以用到java的多型機制,先定義一個公共介面,介面定義支付流程的各個方法,具體的支付方式實現該介面的方法。在控制層,利用spring的注入獲取支付型別和支付方式實現類的引用對映,根據請求需要的支付型別就可以呼叫對應支付方式的方法,以此實現業務的解耦和拓展。後期需要增加支付方式,只需要實現共同介面即可。
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();
}
}