设计模式-结构型-享元

来源:互联网 发布:淘宝网官网下载2017 编辑:程序博客网 时间:2024/06/01 23:46
#pragma once#ifndef FLYWEIGHT_H #define FLYWEIGHT_H #include <string> #include <list> typedef std::string STATE; class Flyweight { public: virtual ~Flyweight(){} STATE GetIntrinsicState(); virtual void Operation(STATE& ExtrinsicState) = 0; protected: Flyweight(const STATE& state) :m_State(state) { } private: STATE m_State; }; class FlyweightFactory { public: FlyweightFactory(){} ~FlyweightFactory(); Flyweight* GetFlyweight(const STATE& key); private: std::list<Flyweight*>    m_listFlyweight; }; class ConcreateFlyweight : public Flyweight { public: ConcreateFlyweight(const STATE& state) : Flyweight(state) { } virtual ~ConcreateFlyweight(){} virtual void Operation(STATE& ExtrinsicState); }; #endif 

#include "StdAfx.h"#include "flyweight_impl.h"#include <iostream> inline STATE Flyweight::GetIntrinsicState() { return m_State; } FlyweightFactory::~FlyweightFactory() { for (std::list<Flyweight*>::iterator iter = m_listFlyweight.begin();iter != m_listFlyweight.end(); ++iter) { delete (*iter);} m_listFlyweight.clear(); } Flyweight* FlyweightFactory::GetFlyweight(const STATE& key) {for (std::list<Flyweight*>::iterator iter = m_listFlyweight.begin();iter != m_listFlyweight.end(); ++iter) { if ((*iter)->GetIntrinsicState() == key) { std::cout << "The Flyweight:" << key << " already exits"<< std::endl; return (*iter); } } std::cout << "Creating a new Flyweight:" << key << std::endl; Flyweight* flyweight = new ConcreateFlyweight(key); m_listFlyweight.push_back(flyweight); return flyweight;} void ConcreateFlyweight::Operation(STATE& ExtrinsicState) { std::cout<<ExtrinsicState<<std::endl;} 

// FlyWeight.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "flyweight_impl.h"#include <stdlib.h>//运用共享技术有效地支持大量细粒度的对象。int _tmain(int argc, _TCHAR* argv[]){FlyweightFactory flyweightfactory; flyweightfactory.GetFlyweight("hello"); flyweightfactory.GetFlyweight("world"); flyweightfactory.GetFlyweight("hello"); system("pause"); return 0;}

原创粉丝点击