Frankfei at 2007/08/02
When learning the locator of objectbuilder, you may know that weakrefdictionary is used as its internal storage structure to implement the object caching mechanism. How is weakrefdictionary implemented? In fact, it uses the Object Adapter mode to adapt a dictioary generic set object to a set that stores weak referenced objects.
Let's review the Object Adapter mode. The following figure shows the structure:
Target role: This is the interface the customer expects. The target can be a specific or abstract class or interface.
Source (adaptee) role: the class to be adapted.
Adapter role: a adaptee object is encapsulated internally to convert the source interface to the target interface.
Let's take a look at the definition of weakrefdictionary:
Public Class Weakrefdictionary < Tkey, tvalue >
{
Private Dictionary < Tkey, weakreference > Inner = New Dictionary < Tkey, weakreference > ();
Public Weakrefdictionary ()
{
}
Public Void Add (tkey key, tvalue value)
{
Tvalue dummy;
If (Tryget (key, Out Dummy ))
Throw New Argumentexception (properties. Resources. keyalreadypresentindictionary );
Inner. Add (key, New Weakreference (encodenullobject (value )));
}
Public Bool Remove (tkey key)
{
ReturnInner. Remove (key );
}
...
}
A small part is listed above.CodeBut we can see the implementation of a simplified Object Adapter mode. The adapter in the structure map is inherited from the target. Here, weakrefdictionary corresponds to the adapter, but weakrefdictionary does not inherit any classes, so I mentioned this is a simplified implementation of the Object Adapter mode. So what is the adaptee object? Obviously, it is a generic dictionary, but the names of methods adapted in this region are the same, such as inner. add (Key, new weakreference (encodenullobject (value); corresponds to public void add (tkey key, tvalue value), inner. remove (key); corresponds to public bool remove (tkey Key), but not as obvious as the adaptee method specificrequest () in the structure diagram is adapted to the Method Request () in the adapter.
Of course, the objectbuilder defines such an adapter: weakrefdictionary is not only the adaptation mentioned above, but I only propose this concept here. The above is just my personal understanding. Please advise if it is inappropriate!