zoukankan      html  css  js  c++  java
  • 设计模式复习-享元模式

    #pragma once
    #include "stdafx.h"
    #include<map>
    #include<set>
    #include<string>
    #include<iostream>
    using namespace std;
    
    /*
    	设计模式-享元模式(Flyweight)
    	运用共享技术有效地支持大量细粒度的对象。
    */
    
    class CFlyweight {//所有具体享元的超类或接口。通过这个接口,Flyweight可以接受并作用域外部状态。
    public:
    	virtual void Operation(const int &nExtrinsicstat) = 0;
    };
    
    class CConcreteFlyweight :public CFlyweight {//为内部状态增加存储空间。
    public:
    	void Operation(const int &nExtrinsicstate) {
    		cout << "ju ti Flyweight:" << nExtrinsicstate << endl;
    	}
    };
    
    class CUnsharedconcreteFlyweight :public CFlyweight {
    public:
    	void Operation(const int &nExtrinsicstate) {
    		cout << "bu gong xiang de ju ti Flyweight:" << nExtrinsicstate << endl;
    	}
    };
    
    class CFlweightFactory {//享元工厂,用来创建并管理Flyweight对象。
    private:
    	map<string, CFlyweight*>mmpFlyweight;
    public:
    	CFlweightFactory() {
    		mmpFlyweight.clear();
    		mmpFlyweight["X"] = new CConcreteFlyweight();
    		mmpFlyweight["Y"] = new CConcreteFlyweight();
    		mmpFlyweight["Z"] = new CConcreteFlyweight();
    	}
    	~CFlweightFactory() {
    		delete mmpFlyweight["X"];
    		delete mmpFlyweight["Y"];
    		delete mmpFlyweight["Z"];
    	}
    	CFlyweight * GetFlyweight(string strKey) {
    		return mmpFlyweight[strKey];
    	}
    };
    
    
    int main() {
    
    	int nExtrinsicstate = 10;
    	CFlweightFactory *pFac = new CFlweightFactory();
    
    	CFlyweight *pNowFlyweight = pFac->GetFlyweight("X");
    	pNowFlyweight->Operation(--nExtrinsicstate);
    
    	pNowFlyweight = pFac->GetFlyweight("Y");
    	pNowFlyweight->Operation(--nExtrinsicstate);
    
    	pNowFlyweight = pFac->GetFlyweight("Z");
    	pNowFlyweight->Operation(--nExtrinsicstate);
    
    	pNowFlyweight = new CUnsharedconcreteFlyweight();
    	pNowFlyweight->Operation(--nExtrinsicstate);
    
    	delete pFac, delete pNowFlyweight;
    	
    	getchar();
    	return 0;
    }

  • 相关阅读:
    HTML5--Video
    线性表简述
    TortoiseSVN使用简介(转)
    JAVA EE(简述)
    WebService
    Java从零开始学四十七(注解简述)
    Java从零开始学四十六(Junit)
    二维数组---模拟斗地主
    Java从零开始学四十五(Socket编程基础)
    Java从零开始学四十四(多线程)
  • 原文地址:https://www.cnblogs.com/csnd/p/12061905.html
Copyright © 2011-2022 走看看