设计模式之—享元模式

享元模式:运用共享技术有效的支持大量细微度的对象。以减少对象的实例个数,减少服务器的负担

内部状态与外部状态:

设计模式之—享元模式_第1张图片

测试用例UML图

设计模式之—享元模式_第2张图片

用户类(User):外部状态

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Flyweight.CLASS
{
    public class User
    {
        private string name;
        public User(string name)
        {
            this.name = name;
        }
        public string Name
        {
            get { return name; }
        }
    }
}
View Code

网站抽象类(WebSite)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Flyweight.CLASS
{
    abstract class WebSite
    {
        public abstract void Use(User user);
    }
}
View Code

具体网站(ConcreateWebSite)继承于WebSite   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Flyweight.CLASS
{
    class ConcreateWebSite :WebSite
    {
        private string name = string.Empty;
        public ConcreateWebSite(string name)
        {
            this.name = name;
        }

        public override void Use(User user)
        {
            Console.WriteLine("网站分类:" + name + " 用户:" + user.Name );
        }
    }
}
View Code

网站工厂类(WebSiteFactory)哈希实现类实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections; //哈希表引用

namespace Flyweight.CLASS
{
    class WebSiteFactory
    {
        //哈希实例类
        private Hashtable flyweights = new Hashtable();
        public WebSite GetWebSiteCategory(string key)
        {
            if (!flyweights.ContainsKey(key))
            {
                flyweights.Add(key, new ConcreateWebSite(key));
            }
            return ((WebSite)flyweights[key]);
        }
        
        //返回实例总数
        public int GetWebSiteConut()
        {
            return flyweights.Count;
        }

    }
}
View Code

测试类(TestMain)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Flyweight.CLASS;
namespace Flyweight
{
    class TestMain
    {
        static void Main(string[] args)
        {
            WebSiteFactory factory = new WebSiteFactory();
            WebSite web1 = factory.GetWebSiteCategory("产品展示");
            web1.Use(new User("小张"));

            WebSite web2 = factory.GetWebSiteCategory("产品展示");
            web2.Use(new User("小李"));

            WebSite web3 = factory.GetWebSiteCategory("产品展示");
            web3.Use(new User("小王"));

            WebSite web4 = factory.GetWebSiteCategory("博客");
            web4.Use(new User("小赵"));

            WebSite web5 = factory.GetWebSiteCategory("博客");
            web5.Use(new User("小胡"));

            Console.WriteLine("网站实例个数为{0}个",factory.GetWebSiteConut());
            Console.ReadLine();
        }
    }
}
View Code

测试结果:实例数为2

设计模式之—享元模式_第3张图片

 

 

 

 

转载于:https://www.cnblogs.com/zxd543/p/3307060.html

你可能感兴趣的:(设计模式之—享元模式)