四。多态机制在实际中的应用

  • 1. 消除类型之间的耦合关系
  • 2. 可替换性
  • 3. 可扩充性
  • 4. 接口性
  • 5. 灵活性
  • 6. 简化性

多态存在的三个必要条件

  • 继承
  • 重写
  • 父类引用指向子类对象

在实际开发工作中,常常遇到一个功能有多种实现方式,比如支付方式,有分微信支付、京东支付、支付宝、银联等支付方式,不同支付方式的大概流程大抵相似,实现细节有所区别。这个时候就可以用到java的多态机制,先定义一个公共接口,接口定义支付流程的各个方法,具体的支付方式实现该接口的方法。在控制层,利用spring的注入获取支付类型和支付方式实现类的引用映射,根据请求需要的支付类型就可以调用对应支付方式的方法,以此实现业务的解耦和拓展。后期需要增加支付方式,只需要实现共同接口即可。

PaymentTypeService.java

/**
 * 支付方式接口
 * @date: 2018年4月23日 下午2:20:09
 */
public interface PaymentTypeService {
 
	public String type();
	
	public void methodA();
	
	public void methodB();

  A

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;
	}
 
}

  实现B: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;
	}
 
}

  实际引用,controller 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();
	}
}

  

posted @ 2020-10-23 09:36  A汉克先生  阅读(403)  评论(0编辑  收藏  举报