• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

【java_ In depth foundation] LinkedHashMap inherits HashMap and implements the design idea behind the

King Wang

1 月 3, 2022

JDK Source code class definition

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

You can find LinkedHashMap extends HashMap already passive Realized Map,
Why do we still need Take the initiative implements Map .
I’ll build my own interface , Mimic business logic , Analyze the problem from a design point of view

Recreate yourself JDK Design

Make clear the relationship between Chu and others , Think about what you should pay attention to when you design this category

establish LinkedHashMap Dependency of

public interface Map {

public void get();
}
public class HashMap implements Map {

@Override
public void get() {

System.out.println("HashMap Realization Map Interface method ");
}
}

LinkedHashMap No initiative Realization Map

public class LinkedHashMap extends HashMap {

@Override
public void get() {

System.out.println("linkedHashMap Of get Method ");
}
}

Use self built LinkedHashMap

public class MyApplication {

/**
* @param map The realization of polymorphism , You can pass in LinkedHashMap perhaps HashMap
*/
private static void doMapAction(Map map){

map.get();
}
public static void main(String[] args) {

LinkedHashMap linkedHashMap = new LinkedHashMap();
doMapAction(linkedHashMap);
}
}

Encounter refactoring task

  • Mission :HashMap To upgrade ,HashMap implements Map Modified into HashMap implements SuperMap

There’s a problem with refactoring

  • problem : modify HashMap Realization ,doMapAction Will report a mistake
 LinkedHashMap linkedHashMap = new LinkedHashMap();
doMapAction(linkedHashMap); // Report errors , The method is declared as Map, linkedHashMap No more Map Polymorphic implementation of 

solve the problem

Solve the above problems , It’s very simple , Only need to LinkedHashMap The class definition Take the initiative Realization Map
public class LinkedHashMap extends HashMap implements Map

Conclusion

From the class diagrams of the two designs :
public class LinkedHashMap extends HashMap
 Insert picture description here
public class LinkedHashMap extends HashMap implements Map
 Insert picture description here
doMapAction(Map map) The business logic of is compatible with HashMap Of changes
 Insert picture description here
implements Map The idea of design is to put Map As LinkHashMap Of Directly dependent on ,
From the semantics of tool class , Method doMapAction(Map map) Don’t care. HashMap Class design , It’s a decoupling .

发表回复