close
1. Used when you need to create a large number of similar objects
2. To reduce memory usage you share objects that are similar in some way rather than creating new ones
Now we are going to create a lot of rectangles with specific
Intrinsic State: Color <---- which all of the rectangle objects are going to share in order to get the
benifts metioned above
Extrinsic State: Size
Before Having Used Flyweight Pattern:
1: public class DrawRect
2: {
3: Graphics g;
4: public DrawRect(Graphics g)
5: {
6: this.g = g;
7: for(int i=0; i<1000000; ++i)
8: {
9: Rectangle rect = new Rectangle(getRandX(), getRandY(), 200, 200);
10: g.FillRectangle(getRandColor(), rect);
11: }
12: }
13: public static Brush[] shapeColor = new Brush[] { Brushes.Orange, Brushes.Red, Brushes.Yellow, Brushes.Blue, Brushes.Pink, Brushes.Cyan, Brushes.Magenta, Brushes.Black, Brushes.Gray };
14:
15: public Brush getRandColor()
16: {
17: Random rand = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);
18: int randInt = rand.Next(9);
19: return shapeColor[randInt];
20: }
21: public static int getRandX()
22: {
23: Random rand = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);
24: int randInt = rand.Next(4);
25: return randInt;
26: }
27: public static int getRandY()
28: {
29: Random rand = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);
30: int randInt = rand.Next(4);
31: return randInt;
32: }
33:
34: }
After Having Used Flyweight Pattern:
Create a rectangle factory that is able to share rectangle objects if their color are the same.
1: public static class RectFactory
2: {
3: static Dictionary<Brush, Rectangle> rectByColor = new Dictionary<Brush, Rectangle>();
4: public static Rectangle GetColorRectangle(Brush color)
5: {
6: Rectangle colorRect;
7:
8: if (rectByColor.ContainsKey(color))
9: colorRect = rectByColor[color];
10: else
11: {
12: Rectangle rect = new Rectangle(DrawRect.getRandX(), DrawRect.getRandY(), 200, 200);
13: rectByColor.Add(color, rect);
14: colorRect = rectByColor[color];
15: }
16:
17:
18: return colorRect;
19: }
20: }
Update DrawRect Class
1: public DrawRect(Graphics g)
2: {
3: this.g = g;
4: for(int i=0; i<1000000; ++i)
5: {
6: Brush color = getRandColor();
7: g.FillRectangle(color, RectFactory.GetColorRectangle(color));
8: }
9: }
References:
全站熱搜
留言列表