设计模式之美:Object Pool(对象池)

 

索引

意图

运用对象池化技术可以显著地提升性能,尤其是当对象的初始化过程代价较大或者频率较高时。

Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high.

结构

参与者

Reusable

  • 类的实例与其他对象进行有限时间的交互。

ReusablePool

  • 管理类的实例。

Client

  • 使用类的实例。

适用性

当以下情况成立时可以使用 Object Pool 模式:

  • 类的实例可重用于交互。
  • 类的实例化过程开销较大。
  • 类的实例化的频率较高。
  • 类参与交互的时间周期有限。

效果

  • 节省了创建类的实例的开销。
  • 节省了创建类的实例的时间。
  • 存储空间随着对象的增多而增大。

相关模式

  • 通常,可以使用 Singleton 模式实现 ReusablePool 类。
  • Factory Method 模式封装了对象的创建的过程,但其不负责管理对象。Object Pool 负责管理对象。

实现

实现方式(一):实现 DatabaseConnectionPool 类。

如果 Client 调用 ObjectPool 的 AcquireReusable() 方法来获取 Reusable 对象,当在 ObjectPool 中存在可用的 Reusable 对象时,其将一个 Reusable 从池中移除,然后返回该对象。如果池为空,则 ObjectPool 会创建一个新的 Reusable 对象。

  1 namespace ObjectPoolPattern.Implementation1
2 {
3 public abstract class ObjectPool<T>
4 {
5 private TimeSpan _expirationTime;
6 private Dictionary<T, DateTime> _unlocked;
7 private Dictionary<T, DateTime> _locked;
8 private readonly object _sync = new object();
9
10 public ObjectPool()
11 {
12 _expirationTime = TimeSpan.FromSeconds(30);
13 _locked = new Dictionary<T, DateTime>();
14 _unlocked = new Dictionary<T, DateTime>();
15 }
16
17 public ObjectPool(TimeSpan expirationTime)
18 : this()
19 {
20 _expirationTime = expirationTime;
21 }
22
23 protected abstract T Create();
24
25 public abstract bool Validate(T reusable);
26
27 public abstract void Expire(T reusable);
28
29 public T CheckOut()
30 {
31 lock (_sync)
32 {
33 T reusable = default(T);
34
35 if (_unlocked.Count > 0)
36 {
37 foreach (var item in _unlocked)
38 {
39 if ((DateTime.UtcNow - item.Value) > _expirationTime)
40 {
41 // object has expired
42 _unlocked.Remove(item.Key);
43 Expire(item.Key);
44 }
45 else
46 {
47 if (Validate(item.Key))
48 {
49 // find a reusable object
50 _unlocked.Remove(item.Key);
51 _locked.Add(item.Key, DateTime.UtcNow);
52 reusable = item.Key;
53 break;
54 }
55 else
56 {
57 // object failed validation
58 _unlocked.Remove(item.Key);
59 Expire(item.Key);
60 }
61 }
62 }
63 }
64
65 // no object available, create a new one
66 if (reusable == null)
67 {
68 reusable = Create();
69 _locked.Add(reusable, DateTime.UtcNow);
70 }
71
72 return reusable;
73 }
74 }
75
76 public void CheckIn(T reusable)
77 {
78 lock (_sync)
79 {
80 _locked.Remove(reusable);
81 _unlocked.Add(reusable, DateTime.UtcNow);
82 }
83 }
84 }
85
86 public class DatabaseConnection : IDisposable
87 {
88 // do some heavy works
89 public DatabaseConnection(string connectionString)
90 {
91 }
92
93 public bool IsOpen { get; set; }
94
95 // release something
96 public void Dispose()
97 {
98 }
99 }
100
101 public class DatabaseConnectionPool : ObjectPool<DatabaseConnection>
102 {
103 private string _connectionString;
104
105 public DatabaseConnectionPool(string connectionString)
106 : base(TimeSpan.FromMinutes(1))
107 {
108 this._connectionString = connectionString;
109 }
110
111 protected override DatabaseConnection Create()
112 {
113 return new DatabaseConnection(_connectionString);
114 }
115
116 public override void Expire(DatabaseConnection connection)
117 {
118 connection.Dispose();
119 }
120
121 public override bool Validate(DatabaseConnection connection)
122 {
123 return connection.IsOpen;
124 }
125 }
126
127 public class Client
128 {
129 public static void TestCase1()
130 {
131 // Create the ConnectionPool:
132 DatabaseConnectionPool pool = new DatabaseConnectionPool(
133 "Data Source=DENNIS;Initial Catalog=TESTDB;Integrated Security=True;");
134
135 // Get a connection:
136 DatabaseConnection connection = pool.CheckOut();
137
138 // Use the connection
139
140 // Return the connection:
141 pool.CheckIn(connection);
142 }
143 }
144 }

设计模式之美》为 Dennis Gao 发布于博客园的系列文章,任何未经作者本人同意的人为或爬虫转载均为耍流氓。

Object Pool的更多相关文章

  1. 设计模式之美:Object Pool(对象池)

    索引 意图 结构 参与者 适用性 效果 相关模式 实现 实现方式(一):实现 DatabaseConnectionPool 类. 实现方式(二):使用对象构造方法和预分配方式实现 ObjectPool ...

  2. .NET Core中Object Pool的简单使用

    前言 复用,是一个重要的话题,也是我们日常开发中经常遇到的,不可避免的问题. 举个最为简单,大家最为熟悉的例子,数据库连接池,就是复用数据库连接. 那么复用的意义在那里呢? 简单来说就是减少不必要的资 ...

  3. What are the differences between Flyweight and Object Pool patterns?

    What are the differences between Flyweight and Object Pool patterns? They differ in the way they are ...

  4. Object Pool 对象池的C++11使用(转)

    很多系统对资源的访问快捷性及可预测性有严格要求,列入包括网络连接.对象实例.线程和内存.而且还要求解决方案可扩展,能应付存在大量资源的情形. object pool针对特定类型的对象循环利用,这些对象 ...

  5. 对象池模式(Object Pool Pattern)

    本文节选自<设计模式就该这样学> 1 对象池模式的定义 对象池模式(Object Pool Pattern),是创建型设计模式的一种,将对象预先创建并初始化后放入对象池中,对象提供者就能利 ...

  6. Unity Object Pool完全体

    using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public ...

  7. [译]Unity3D内存管理——对象池(Object Pool)

    原文地址:C# Memory Management for Unity Developers (part 3 of 3), 其实从原文标题可以看出,这是一系列文章中的第三篇,前两篇讲解了从C#语言本身 ...

  8. Java小对象的解决之道——对象池(Object Pool)的设计与应用

    一.概述 面向对象编程是软件开发中的一项利器,现已经成为大多数编程人员的编程思路.很多高级计算机语言也对这种编程模式提供了很好的支持,例如C++.Object Pascal.Java等.曾经有大量的软 ...

  9. thinking in object pool

    1.背景 对象池为了避免频繁创建耗时或耗资源的大对象,事先在对象池中创建好一定数量的大对象,然后尽量复用对象池中的对象,用户用完大对象之后放回对象池. 2.问题 目前纵观主流语言的实现方式无外乎3个步 ...

随机推荐

  1. 笔试题&amp;面试题:设计一个复杂度为n的算法找到单向链表倒数第m个元素

    设计一个复杂度为n的算法找到单向链表倒数第m个元素.最后一个元素假定是倒数第0个. 提示:双指针查找 相对于双向链表来说,单向链表仅仅能从头到尾依次訪问链表的各个节点,所以假设要找链表的倒数第m个元素 ...

  2. Lake Counting (DFS)

    N*M的园子,雨后积起了水.八连通的积水背认为是连接在一起的.请求出园子里总共有多少水洼? dfs(Depth-First  Search)  八个方向的简单搜索.... 深度优先搜索从最开始的状态出 ...

  3. 使用Mockito进行单元测试【1】——mock and verify[转]

    本文转自:http://qiuguo0205.iteye.com/blog/1443344 1. 为什么使用Mockito来进行单元测试? 回答这个问题需要回答两个方面,第一个是为什么使用mock?m ...

  4. 第20章 状态模式(State Pattern)

    原文 第20章 状态模式(State Pattern) 状态模式  概述:   当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类. 状态模式主要解决的是当控制一个对象状态的条件表 ...

  5. crawler_浅谈网络爬虫

    题记: 1024,今天是个程序猿的节日 ,哈哈,转为正题,从事了一线网络爬虫开发有近1000天.简单阐述下个人对网络爬虫的理解. 提纲: 1:是什么 2:能做什么 3:怎么做 4:综述 1:是什么 w ...

  6. IOS新手教程(二)-控制流

    int main(){ //2.控制流 //2.1 if语句 //1. if(expression){ } //2. if(expression){ }else{ } //3.能够有0个或是多个els ...

  7. iOS 开发者必不可少的 75 个工具

    如果你去到一位熟练的木匠的工作室,你总是能发现他/她有一堆工具来完成不同的任务. 软件开发同样如此.你可以从软件开发者如何使用工具中看出他水准如何.有经验的开发者精于使用工具.对你目前所使用的工具不断 ...

  8. 【solr这四个主题】在Tomcat 部署Solr4.x

    1.安装Tomcat (1)下载并解压缩到/opt/tomcat在 # cd /opt/jediael # tar -zxvf apache-tomcat-7.0.54.tar.gz # mv apa ...

  9. white-space的值

    white-space的值:normal 默认.空白会被浏览器忽略.pre 空白会被浏览器保留.其行为方式类似 HTML 中的 标签.nowrap 文本不会换行,文本会在在同一行上继续,直到遇到 标签 ...

  10. Android4.3引入的UiAutomation新框架官方简介

    译者序:Google在Android 4.3发布时提供了一套新的UiAutomation框架来支持用户界面自动化测试,该框架通过运用已有的Accessibility APIs来模拟用户跟设备用户界面的 ...