• 设计模式-享元模式


    享元模式Flyweight):

        运用共享技术有效地支持大量细粒度的对象。


    1.如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用;还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。
    2.享元模式可以避免大量非常相似类的开销。在程序设计中,有时就能够受到大幅度地减少需要实例化的类的数量。如果能把那些参数转移到类实例的外面,在方法调用时将他们传递进来,就可以通过共享大幅度地减少单个实例的数目。
    享元模式实现代码
    #pragma once
    #include <map>
    #include <string>
    #include <iostream>
    using namespace std;
    
    //Flyweight类,它是所有具体享元的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。
    class CFlyweight
    {
    public:
    	virtual void Operation(int nExtrinsicstate) = 0;
    };
    
    //CConcreteFlyweight是继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
    class CConcreteFlyweight : public CFlyweight
    {
    public:
    	void Operation(int nExtrinsicstate)
    	{
    		cout<<"ju ti Flyweight:"<<nExtrinsicstate<<endl;
    	}
    };
    
    //UnsharedConcreteFlyweight是指那些不需要共享的Flyweight子类。因为Flyweight接口共享称为可能,
    //但它并不强制共享。
    class CUnsharedConcreteFlyweight:public CFlyweight
    {
    public:
    	void Operation(int nExtrinsicstate)
    	{
    		cout<<"bu gong xiang de ju ti Flyweight:"<<nExtrinsicstate<<endl;
    	}
    };
    
    //FlyweightFactiry,是一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理地共享
    //Flyweight,当用户请求一个Flyweigth时,FlyweightFactory对象提供一个已经创建的实例或者创建一个。
    class CFlyweightFactory
    {
    private:
    	map<string ,CFlyweight *>m_mpFlyweight;
    public:
    	CFlyweightFactory()
    	{
    		m_mpFlyweight.clear();
    		m_mpFlyweight["X"] = new CConcreteFlyweight();
    		m_mpFlyweight["Y"] = new CConcreteFlyweight();
    		m_mpFlyweight["Z"] = new CConcreteFlyweight();
    	}
    	~CFlyweightFactory()
    	{
    		delete m_mpFlyweight["X"];
    		delete m_mpFlyweight["Y"];
    		delete m_mpFlyweight["Z"];
    	}
    	CFlyweight * GetFlyweight(string strKey)
    	{
    		return m_mpFlyweight[strKey];
    	}
    };
    客户端调用
    #include "stdafx.h"
    #include <iostream>
    #include <windows.h>
    #include "FlyweightMode.h"
    
    using namespace std;
    
    int main()
    {
    	int nExtrinsicstate = 22;
    	CFlyweightFactory *pF = new CFlyweightFactory();
    
    	CFlyweight *pNowFlyweight = pF->GetFlyweight("X");
    	pNowFlyweight->Operation(--nExtrinsicstate);
    
    	pNowFlyweight = pF->GetFlyweight("Y");
    	pNowFlyweight->Operation(--nExtrinsicstate);
    
    	pNowFlyweight = pF->GetFlyweight("Z");
    	pNowFlyweight->Operation(--nExtrinsicstate);
    
    	CUnsharedConcreteFlyweight *pUF = new CUnsharedConcreteFlyweight();
    	pUF->Operation(--nExtrinsicstate);
    
    	delete pUF;
    	delete pF;
    
       return 0;
    }

    执行结果


  • 相关阅读:
    关键字: simpledateformat24小时 格式串
    浅谈DB2在线分析处理函数
    Java中的final关键字
    TestNG注解使用技巧
    java之静态方法,静态变量
    CssSelector之selenium元素定位
    收藏,常用正则表达式
    正则表达式小结
    [转]java中文乱码的解决
    多叉树结构:JSON数据解析(一)
  • 原文地址:https://www.cnblogs.com/csnd/p/12062319.html
Copyright © 2020-2023  润新知