Today, I studied the flyweight mode and found that I had a deep misunderstanding of this mode.
This mode is used to solve the problem: the overhead of a large number of very similar classes.
For example, in a program, a folder class has different names and coordinates, and the others are identical, therefore, we can import the name and location as external data to the drawing method for plotting. Therefore, we only need an instance of folder, you can draw Multiple folder of the same instance, instead of implementing these parameters within a class, thus avoiding the creation of a large number of classes.
First look at the class diagram
The Code is as follows:
public interface IFlyWeight{ void Load(); void Display();}
public class FlyWeight:IFlyWeight{ Image m_image; public void Load(string fileName) { Image image = Bitmap.FromFile(fileName); } public void Display() { //Show image }}
public class FlyweightFactory { Dictionary<string, IFlyWeight> m_dictionary = new Dictionary<string, IFlyWeight>(); public FlyweightFactory() { m_dictionary.Clear(); } public IFlyWeight this[string index] { get { if (!m_dictionary.ContainsKey(index)) m_dictionary[index] = new FlyWeight(); return m_dictionary[index]; } } }
The purpose of this factory is to find one at the factory when flyweight is required. If there is no such factory, a new one will be created.
Here we can see that flyweight does not reduce object creation, because each ifryweight is different, so flyweight can only reduce the creation of the same object (flyweight factory ).
Iflkweight solves the problem of sharing.
For example, if an image display program uses the iflyweight mode to display different images, it cannot reflect the advantage of reducing objects and the number of image objects to be generated, or how much is generated. However, when there are a large number of identical images in our program, this will play a role. We use the same image object and then use different display parameters (such as coordinate X, y.
This mode is similar to creating strings. When you create two identical strings, they are actually a content.