flyweight-photogroup.cs

本文通过一个具体的享元模式应用实例,展示了如何利用共享状态减少内存中对象的数量,从而达到节省资源的目的。代码中实现了图片分组加载及展示功能,通过享元工厂管理重复的对象,避免了大量相似对象的冗余存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  using System;
  using System.Collections.Generic;
  using System.Drawing;
  using System.Windows.Forms;
  using FlyweightPattern;
 
  // The Client
  class Client {
    // Shared state - the images
    static FlyweightFactory album =  new FlyweightFactory();
 
    // Unshared state - the groups
    static Dictionary <string,List<string>> allGroups =
             new Dictionary <string,List<string>> ();  
 
    public void LoadGroups () {
      var myGroups = new [] {
          new  {Name = "Garden",  
                    Members =   new [] {"pot.jpg", "spring.jpg", "barbeque.jpg", "flowers.jpg"}},
          new  {Name = "Italy",  
                    Members =   new [] {"cappucino.jpg","pasta.jpg", "restaurant.jpg", "church.jpg"}},
          new  {Name = "Food",  
                    Members =  new [] {"pasta.jpg", "veggies.jpg", "barbeque.jpg","cappucino.jpg","lemonade.jpg" }},
          new  {Name = "Friends",  
                    Members = new [] {"restaurant.jpg", "dinner.jpg"}}
      };

      // Load the Flyweights, saving on shared intrinsic state
      foreach (var g in myGroups) {
        allGroups.Add(g.Name,new List <string>());
        foreach (string filename in g.Members) {
          allGroups[g.Name].Add(filename);
          album[filename].Load(filename);
        }
      }
    }
 
    public void DisplayGroups (Object source, PaintEventArgs e) {
      // Display the Flyweights, passing the  unshared state
      var row = 0;
      foreach(string g in allGroups.Keys) {
        var col = 0;
        e.Graphics.DrawString(g,
           new Font("Arial", 16),
           new SolidBrush(Color.Black),
           new PointF(0, row*130+10));
        foreach (string filename in allGroups[g]) {
          album[filename].Display(e, row, col);
          col++;
        }
        row++;
      }
    }
  }
    
  class Window : Form {
    Window() {
      this.Height = 600;
      this.Width = 600;
      this.Text = "Picture Groups";
      Client client = new Client();
      client.LoadGroups();
      this.Paint +=  new PaintEventHandler (client.DisplayGroups);
    }
 
    static void Main () {
      Application.Run(new Window());
    }
  }

转载于:https://www.cnblogs.com/shihao/archive/2012/05/11/2496307.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值