This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

A preface

Speaking of map, in fact, many people are very headache, because compared with List, map is less readable, therefore, I used to use List more in the development, but in fact, map still has a lot of benefits, now I introduce a map very practical processing method

The second scene

When you pay, there are two payment methods, Alipay and wechat Pay. There will be different logic for the two payment methods, so you might want to create two different classes for the two payment methods and determine which payment method to use based on the incoming type.

boolean isZFB =true; boolean isWX =true; If (isWX){// if(isWX){// call wechat implementation}Copy the code

One problem with this is that as the number of payment methods increases, the number of ifs increases and it’s easy to end up as noodle code. This is where map solves the problem.

Three application

Let’s start by creating an abstract interface (using a normal real-world example)

 public interface IEdiSender {}
 
Copy the code

Create an implementation class for the interface

public class Csm001ShipEdiService implements IEdiSender{ public static final String EDI_TYPE = "CSM001"; @Override public String getEdiType() { return EDI_TYPE; } } public class Csm002ShipEdiService implements IEdiSender{ public static final String EDI_TYPE = "CSM002"; @Override public String getEdiType() { return EDI_TYPE; }}Copy the code

The type code is then mapped to the implementation instance during Spring initialization

@Service public class EdiSenderProvider implements ApplicationContextAware { private Map<String, IEdiSender> iEdiSenderMap; public IEdiSender getEdiSenderByType(String ediType) { return iEdiSenderMap.get(ediType); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Map<String,  IEdiSender> beansOfType = applicationContext.getBeansOfType(IEdiSender.class); iEdiSenderMap = new HashMap<String, IEdiSender>(); for (IEdiSender iEdiSender : beansOfType.values()) { iEdiSenderMap.put(iEdiSender.getEdiType(), iEdiSender); }}}Copy the code

We can then call the Beanfactory Map and get the instance directly from the type. This is very useful.