- 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
- Additional Reading
Solution Introduction and the Flyweight Pattern
I’ll use the flyweight design pattern to describe an economical way of managing link IP addresses. My flyweight will consist of a generic class that represents a link of a given technology (MPLS, in this case), along with the range of IP addresses for that link. In this problem domain, extrinsic link attributes are adjacent interfaces, nodes, and IP address ranges; intrinsic link attributes consist solely of technology type.
Before we get into the code, let’s briefly review a more classical use of the flyweight pattern, drawn from Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma et al. This should help cement the concept.
A commonly described application for the flyweight pattern is in document text management. Rather than modeling each character in a document as an independent object, the problem is reduced to more manageable proportions by dividing character object attributes into intrinsic and extrinsic categories. Intrinsic attributes stay with the object and extrinsic attributes can be stored elsewhere. The flyweight is a shared object that contains the intrinsic attributes and can be used simultaneously in multiple contexts.
A document editor can create a flyweight for each letter of the alphabet—a finite set. The character code (A, B, C, etc.) is intrinsic to each character, whereas the position in the document and the font style are extrinsic. The document provides the context for the position and style.
Most documents use a limited set of characters and font combinations. In general, the number of different characters in the document is far less than the total number of characters in the document. Once this problem characteristic is identified, we have a candidate for the flyweight.