1. 程式人生 > >基金買入多重校驗之設計模式應用

基金買入多重校驗之設計模式應用

github專案下載地址

情景描述:

在基金的買入(認購、申購、定投)中,會有很多前置業務校驗,例如:基金狀態、業務狀態、最小限額、最大限額等等十多個校驗,認申定3種買入操作中大多數校驗是共用的,也有一部分是獨有的,這些校驗之間方法中存在相互依賴關係。如果把這些校驗封裝成公共方法一一呼叫,程式碼即繁瑣且不易維護,運用設計模式進行解耦大大提高程式碼可閱讀性。

建立介面

public interface Validator<T extends PurchaseDTO> {
	public void check(T t) throws Exception;
}

建立標記介面

public interface Buy020Validator extends Validator {
}
public interface Buy022Validatorextends Validator {
}
public interface Buy039Validator extends Validator {
}

建立公用抽象類

public abstract class PurchaseVaildatorBase {
	@Autowired
	protected ClientService clientService;
	
	private ClientInfoDTO clientInfoDTO;
	
	protected ClientInfoDTO getClientInfo(PurchaseDTO purchaseDTO) {
		if (clientInfoDTO != null) {
			return clientInfoDTO;
		}
		// TODO 根據clientid獲取ClientInfoDTO
		String clientid = purchaseDTO.getClientid();
		clientInfoDTO = clientService.queryClientById(clientid);
		return clientInfoDTO;
	}
}

建立具體校驗類

@Component
@Order(1)
@Scope("prototype")
public class BanckCardValidator extends PurchaseVaildatorBase implements Buy020Validator, Buy039Validator {

	@Override
	public void check(PurchaseDTO purchaseDTO) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BanckCardValidator");
	}
}
@Component
@Order(2)
@Scope("prototype")
public class AmountValidator extends PurchaseVaildatorBase implements Buy020Validator, Buy022Validator, Buy039Validator {
	@Override
	public void check(PurchaseDTO purchaseDTO) throws Exception {
		// TODO Auto-generated method stub
		ClientInfoDTO clientInfo = getClientInfo(purchaseDTO);
		System.out.println("AmountValidator:"+new Gson().toJson(clientInfo));
	}
}

@Component
@Order(3)
@Scope("prototype")
public class BusinessCodeValidator extends PurchaseVaildatorBase implements Buy020Validator, Buy022Validator {

	@Override
	public void check(PurchaseDTO purchaseDTO) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BusinessCodeValidator");
	}
}

@Component
@Order(4)
@Scope("prototype")
public class TaValidator extends PurchaseVaildatorBase implements Buy020Validator, Buy022Validator, Buy039Validator {

	@Override
	public void check(PurchaseDTO purchaseDTO) throws Exception {
		// TODO Auto-generated method stub
		ClientInfoDTO clientInfo = getClientInfo(purchaseDTO);
		System.out.println("TaValidator:"+new Gson().toJson(clientInfo));
	}
}

具體結構如下:

在這裡插入圖片描述

測試類如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MainApplication.class)
public class AppTest {

	@Autowired
	private BuyService buyService;

	@Test
	public void fun1() {
		try {
			PurchaseDTO purchaseDTO = new PurchaseDTO();
			purchaseDTO.setBusinessCode("020");
			purchaseDTO.setBankAccount("12312312");
			purchaseDTO.setClientid("1234567890");
			Respones respones = buyService.purchase(purchaseDTO);
			System.out.println(new Gson().toJson(respones));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

測試結果:

在這裡插入圖片描述