- Protecting Valuable Resources
- Interfaces: Action-Packed Entities
- Configuring IP Addresses
- Solution Introduction and the Flyweight Pattern
- A Generic Network Link
- A Generic Network Link Context
- A Real Network Link
- The GenericLink Implementation
- The GenericLinkContext Implementation
- The RealLink Implementation
- Bringing the Code Together
- Conclusion
- Additional Reading
The GenericLinkContext Implementation
Listing 6 holds the GenericLinkContext implementation. The bulk of the code in this class is used to manipulate the data structure that stores link-specific IP address ranges. Remember, each concrete link is allocated a slot in the array maintained by the GenericLinkContext object. So the context spends most of its time handling client requests related to this data structure—allocating slots, and adding or retrieving data.
Listing 6 The GenericLinkContext class implementation.
GenericLinkContext::GenericLinkContext(void) { SetNextFreeSlot(-1); } GenericLinkContext::~GenericLinkContext(void) { } int GenericLinkContext::GetNextFreeSlot(void) { if (nextFreeSlot < MAX_ARRAY_LENGTH) return ++nextFreeSlot; else return nextFreeSlot; } void GenericLinkContext::SetNextFreeSlot(int theNextFreeSlot) { nextFreeSlot = theNextFreeSlot; } void GenericLinkContext::SetAddressRange(int slot, char* baseAddress, int offset, int range) { AddressRangeArray[slot].baseRangeAddress = baseAddress; AddressRangeArray[slot].addressOffset = offset; AddressRangeArray[slot].addressRange = range; } char* GenericLinkContext::GetBaseAddress(int slot) { return AddressRangeArray[slot].baseRangeAddress; } int GenericLinkContext::GetAddressOffset(int slot) { return AddressRangeArray[slot].addressOffset; } int GenericLinkContext::GetAddressRange(int slot) { return AddressRangeArray[slot].addressRange; }