Design Patterns -- Flyweight

2019-04-15 17:48发布

The intent of Flyweight is to use sharing to support large numbers of fine-grained objects efficiently. see pic:   A preliminary step in applying the Flyweight pattern is to extract the immutable part of an object so that this part can be shared. The class's immutablity relies on the immutability of its attributes. (Maybe the attributs will not change once the object is created) Extracting the immutable part of an object is half of the battle in applying the Flyweight pattern. The remaining work includes creating a flyweight factory that instantiates flyweights and that arranges for clients to share them. And we also have to ensure that clients must use our factory instead of the constractor (use protected access of constructor and make another factory class in the same package). To ensure that the factory class  is absolutely the only class that can create new instances, we can apply an inner class, define the class of the object in the factory class. (And make the former one static member class.)