- 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 RealLink Implementation
Listing 7 shows the implementation of the RealLink class. Notice the way the constructor initializes the constructor for the base class (GenericLink). The RealLink constructor also provides a value for the technologyType data member. Most of the action in RealLink occurs in the GetAllIPAddresses() member function. (Please note that this method has not been optimized, in order to make it easier to follow.)
Let’s break down the operation of GetAllIPAddresses() into four easy stages:
- Getting the address range details from the GenericLinkContext object
- Getting and duplicating the base address
- Inserting the minus sign (-) to indicate that this is an address range, such as 10.81.1.x - 10.81.1.x
- Replacing the x values with the offset and range values to produce 10.81.1.0 - 10.81.1.7
Step 1 is executed with calls to member functions:
- GetAddressOffset()
- GetAddressRange()
- GetBaseAddress()
Step 2 is executed using calls to strncat() to concatenate the strings. Step 3 is achieved by a simple while loop that searches for the letter x. Finally, step 4 is achieved by converting the addressOffset integer value into its character equivalent.
Listing 7 The RealLink class implementation.
RealLink::RealLink(char* aTechnologyType, char* nodeA, char* nodeB, char* ifA, char* ifB, GenericLinkContext* aLinkContext) : GenericLink(aLinkContext, nodeA, nodeB, ifA, ifB) { technologyType = aTechnologyType; } RealLink::~RealLink(void) { } void RealLink::GetAllIPAddresses(char* ipAddressRange) { memset(ipAddressRange, ’\0’, BUFFER_LENGTH); int addressOffset = linkContext->GetAddressOffset(mySlotNumber); int addressRange = linkContext->GetAddressRange(mySlotNumber); strncat(ipAddressRange, linkContext->GetBaseAddress(mySlotNumber), strlen(linkContext->GetBaseAddress(mySlotNumber))); strncat(ipAddressRange, " - ", strlen(" - ")); strncat(ipAddressRange, linkContext->GetBaseAddress(mySlotNumber), strlen(linkContext->GetBaseAddress(mySlotNumber))); int index = 0; while (ipAddressRange[index] != ’x’) index++; ipAddressRange[index] = addressOffset + ’0’; while (ipAddressRange[index] != ’x’) index++; ipAddressRange[index] = addressRange + ’0’; }
Let’s finish off by running the complete program and viewing the results.