23种设计模式之十(结构型模式)Flyweight模式

一、简介

        Flyweight 享元模式为了解决的问题是:面向对象很好地解决了系统抽象性的问题,但在在某些特殊的应用中,如果一个应用程序使用了太多的对象,采用面向对象会给系统带来难以承受的内存开销,特别是对于大量轻量级(细粒度)的对象。比如图形应用中的图元等对象、字处理应用中的字符对象等。同时也可以对象的状态分为“外部状态”和“内部状态”,把可以被共享(不会变化)的状态作为内部状态存储在对象中,而外部对象例如字体、大小等变化的参数)可以在适当的时候将外部对象作为参数传递给对象(例如在显示的时候,将字体、大小等信息传递给对象)。

       Flyweight模式在实现过程中主要是要为共享对象提供一个对象池,其中有一个FlyweightFactory的对象构造工厂,用户Flyweight需要一个对象的时候,会通过工厂接口GetFlyweight请求返回对象,工厂会通过对象池遍历池中的对象,如果有直接返回,没有于是创建。

       Flyweight 模式典型的结构图为:


        Flyweight 模式中有一个类似 Factory 模式的对象构造工厂FlyweightFactory,当客户程序员(Client)需要一个对象时候就会向 FlyweightFactory 发出请求对象的消息 GetFlyweight()消息,FlyweightFactory 拥有一个管理、存储对象的“仓库”(或者叫对象池,vector 实现),GetFlyweight()消息会遍历对象池中的对象,如果已经存在则直接返回给 Client,否则创建一个新的对象返回给 Client。

二、详解

1、代码实现

(1)代码flyweight.h:

#ifndef _FLYWEIGHT_H_
#define _FLYWEIGHT_H_
#include <string>
using namespace std;

class Flyweight
{
	  public:
	  	  virtual ~Flyweight();
	  	   //操作外部状态extrinsicState
	  	  virtual void Operation(const string &extrinsicState) = 0;
	  	  string GetIntrinsicState();
	  protected:
	  	  Flyweight(string intrinsicState);
	  private:
	  	  string _intrinsicState;
};

class ConcreteFlyweight : public Flyweight
{
	  public:
	  	  ConcreteFlyweight(string intrinsicState);
	  	  ~ConcreteFlyweight();
	  	  //实现接口函数
	  	  void Operation(const string &extrinsicState);
	  protected:
	  private:
};

class UnsharedConcreteFlyweight : public Flyweight
{
    public:    
        virtual void Operation(const string& extrinsicState);
        UnsharedConcreteFlyweight(string intrinsicState);
        ~UnsharedConcreteFlyweight();
};
#endif
(2)代码flyweight.cpp:

#include <iostream>
#include "flyweight.h"
using namespace std;

Flyweight::Flyweight(string intrinsicState)
{
	  _intrinsicState = intrinsicState;
}

Flyweight::~Flyweight()
{
}

void Flyweight::Operation(const string &extrinsicState)
{
}

string Flyweight::GetIntrinsicState()
{
	  return this->_intrinsicState;
}

ConcreteFlyweight::ConcreteFlyweight(string intrinsicState)
	  : Flyweight(intrinsicState)
{
	  cout<<"ConcreteFlyweight Build..."<<intrinsicState<<endl;
}

ConcreteFlyweight::~ConcreteFlyweight()
{
}

void ConcreteFlyweight::Operation(const string &extrinsicState)
{
	  cout<<"ConcreteFlyweight:内蕴["<<GetIntrinsicState()<<"]外蕴["<<extrinsicState<<"]"<<endl;
}

UnsharedConcreteFlyweight::UnsharedConcreteFlyweight(string intrinsicState)
    : Flyweight(intrinsicState)
{
}

UnsharedConcreteFlyweight::~UnsharedConcreteFlyweight()
{
}

void UnsharedConcreteFlyweight::Operation(const string& extrinsicState)
{
    cout <<"---extrinsicState:"<<extrinsicState<<endl;
}
(3)代码flyweightfactory.h:
#ifndef _FLYWEIGHTFACTORY_H_
#define _FLYWEIGHTFACTORY_H_

#include <string>
#include <iostream>
#include <vector>
#include <cassert>
#include "flyweight.h"
using namespace std;

class FlyweightFactory
{
	  public:
	  	  FlyweightFactory();
	  	  ~FlyweightFactory();
	  	  //获得一个请求的Flyweight对象
	  	  Flyweight *GetFlyweight(const string &key);
	  protected:
	  private:
	  	  //保存内部状态对象的容器
	  	  vector<Flyweight *>_fly;
};

#endif
(4)代码flyweightfactory.cpp:
#include "flyweightfactory.h"

FlyweightFactory::FlyweightFactory()
{
}

FlyweightFactory::~FlyweightFactory()
{
	  vector<Flyweight *>::iterator it = _fly.begin();
	  for (; it != _fly.end(); it++) {
	  	  delete *it;
	  	  *it = NULL;
	  }
}

Flyweight *FlyweightFactory::GetFlyweight(const string &key)
{
	  vector<Flyweight *>::iterator it = _fly.begin();
	  for (; it != _fly.end(); it++) {
	      if ((*it)->GetIntrinsicState() == key) {
	          cout<<"---already created by users..."<<key<<endl;
            return *it;
	      }
	  }
	  Flyweight *fn = new ConcreteFlyweight(key);
    _fly.push_back(fn);
    return fn;
}
(4)代码main.cpp:
#include <iostream>
#include "flyweight.h"
#include "flyweightfactory.h"
using namespace std;

int main()
{
	  //外部状态extrinsicState
	  string extrinsicState = "ext";
	  FlyweightFactory *fc = new FlyweightFactory();
    Flyweight *fw1 = fc->GetFlyweight("hello");
    //应用外部状态
    fw1->Operation(extrinsicState);
    
    Flyweight *fw2 = fc->GetFlyweight("world!");
    Flyweight *fw3 = fc->GetFlyweight("hello");

    delete fc;
    fc = NULL;
	  return 0;
}
(5)makefile:
CFLAGS = -g
DEFINED = #-D _VERSION
LIBS = 
CC = g++
INCLUDES = -I./
OBJS= main.o flyweight.o flyweightfactory.o
TARGET= main
all:$(TARGET)

$(TARGET):$(OBJS)
	$(CC) $(CFLAGS) -o $@ $(OBJS)

.SUFFIXES:.o .h
.SUFFIXES:.cpp .o
.cpp.o:
	$(CC) $(DEFINED) -c $(CFLAGS) -o $@ $<

ok:
	./$(TARGET)
clean:
	rm -f $(OBJS) $(TARGET) core *.log

2、运行结果

(Centos6.3系统中运行结果:)


三、总结

(1)Flyweight 模式在实现过程中主要是要为共享对象提供一个存放的“仓库”(对象池),这里是通过 C++ STL 中 Vector 容器,当然就牵涉到 STL 编程的一些问题(Iterator 使用等)。

(2)对象“仓库”(对象池)的管理策略(查找、插入等),这里是通过直接的顺序遍历实现的可以使用其他更加有效的索引策略,例如例如 Hash 表的管理策略。

(3)源码已经打包上传到csdn上可登录下载(http://download.csdn.net/detail/taiyang1987912/8420399)。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java设计模式是一组经过实践验证的面向对象设计原则和模式,可以帮助开发人员解决常见的软件设计问题。下面是常见的23种设计模式: 1. 创建型模式(Creational Patterns): - 工厂方法模式Factory Method Pattern) - 抽象工厂模式(Abstract Factory Pattern) - 单例模式(Singleton Pattern) - 原型模式(Prototype Pattern) - 建造者模式(Builder Pattern) 2. 结构型模式(Structural Patterns): - 适配器模式(Adapter Pattern) - 桥接模式(Bridge Pattern) - 组合模式(Composite Pattern) - 装饰器模式(Decorator Pattern) - 外观模式(Facade Pattern) - 享元模式Flyweight Pattern) - 代理模式(Proxy Pattern) 3. 行为型模式(Behavioral Patterns): - 责任链模式(Chain of Responsibility Pattern) - 命令模式(Command Pattern) - 解释器模式(Interpreter Pattern) - 迭代器模式(Iterator Pattern) - 中介者模式(Mediator Pattern) - 备忘录模式(Memento Pattern) - 观察者模式(Observer Pattern) - 状态模式(State Pattern) - 策略模式(Strategy Pattern) - 模板方法模式(Template Method Pattern) - 访问者模式(Visitor Pattern) 4. 并发型模式(Concurrency Patterns): - 保护性暂停模式(Guarded Suspension Pattern) - 生产者-消费者模式(Producer-Consumer Pattern) - 读写锁模式(Read-Write Lock Pattern) - 信号量模式(Semaphore Pattern) - 线程池模式(Thread Pool Pattern) 这些设计模式可以根据问题的特点和需求来选择使用,它们提供了一些可复用的解决方案,有助于开发高质量、可维护且易于扩展的软件系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乌托邦2号

博文不易,支持的请给予小小打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值