当前位置: 首页 > 编程日记 > 正文

Unity应用架构设计(9)——构建统一的 Repository

谈到 『Repository』 仓储模式,第一映像就是封装了对数据的访问和持久化。Repository 模式的理念核心是定义了一个规范,即接口『Interface』,在这个规范里面定义了访问以及持久化数据的行为。开发者只要对接口进行特定的实现就可以满足对不同存储介质的访问,比如存储在Database,File System,Cache等等。软件开发领域有非常多类似的想法,比如JDBC就是定义了一套规范,而具体的厂商MySql,Oracle根据此开发对应的驱动。

Unity 中的Repository模式

在Unity 3D中,数据的存储其实有很多地方,比如最常见的内存可以高速缓存一些临时数据,PlayerPrefs可以记录一些存档信息,TextAsset可以存一些配置信息,日志文件可以用IO操作写入,关系型数据结构可以使用Sqlite存储。Repository 是个很抽象的概念,操作的数据也不一定要在本地,很有可能是存在远程服务器,所以也支持以Web Service的形式对数据进行访问和持久化。

根据上述的描述,Repository 模式的架构图如下所示:

o_Untitled.png

可以看到,通过统一的接口,可以实现对不同存储介质的访问,甚至是访问远程数据。

定义Repository规范

Repository的规范就是接口,这个接口功能很简单,封装了数据增,删,查,改的行为:

public interface IRepository<T> where T:class,new()
{void Insert(T instance);void Delete(T instance);void Update(T instance);IEnumerable<T> Select(Func<T,bool> func );
}

这只是一个最基本的定义,也是最基础的操作,完全可以再做扩展。

值得注意的是,对于一些只读数据,比如TextAssets,Insert,Delete,Update 往往不用实现。这就违反了『里式替换原则』,解决方案也很简单,使用接口隔离,对于只读的数据只实现 ISelectable 接口。但这往往会破环了我们的Repository结构,你可能会扩展很多不同的行为接口,从代码角度很优化,但可读性变差。所以,在uMVVM框架中,我为了保证Repository的完整性和可读性,选择违背『里式替换原则』。

开发者根据不同的存储介质,决定不同的操作方法,这是显而易见的,下面就是一些常见Repository实现。

定义UnityResourcesRepository:用来访问Unity的资源TextAssets

public class UnityResourcesRepository<T> : IRepository<T> where T : class, new()
{//...省略部分代码...public IEnumerable<T> Select(Func<T, bool> func){List<T> items = new List<T>();try{TextAsset[] textAssets = Resources.LoadAll<TextAsset>(DataDirectory);for (int i = 0; i < textAssets.Length; i++){TextAsset textAsset = textAssets[i];T item = Serializer.Deserialize<T>(textAsset.text);items.Add(item);}}catch (Exception e){throw new Exception(e.ToString());}return items.Where(func);}
}

定义PlayerPrefsRepository:用来访问和持久化一些存档相关信息

public class PlayerPrefsRepository<T> : IRepository<T> where T : class, new()
{//...省略部分代码...public void Insert(T instance){try{string serializedObject = Serializer.Serialize<T>(instance, true);PlayerPrefs.SetString(KeysIndexName, serializedObject);}catch (Exception e){throw new Exception(e.ToString());}}}

定义FileSystemRepository:用来访问和持久化一些日志相关信息

public class FileSystemRepository<T> : IRepository<T> where T:class,new()
{   //...省略部分代码...public void Insert(T instance){try{string filename = GetFilename(Guid.NewGuid());if (File.Exists(filename)){throw new Exception("Attempting to insert an object which already exists. Filename=" + filename);}string serializedObject = Serializer.Serialize<T>(instance, true);using (StreamWriter stream = new StreamWriter(filename)){stream.Write(serializedObject);}}catch (Exception e){throw new Exception(e.ToString());}}}

定义MemoryRepository:用来高速缓存一些临时数据

public class MemoryRepository<T> : IRepository<T> where T : class, new()
{//...省略部分代码...private Dictionary<object, T> repository = new Dictionary<object, T>();public MemoryRepository(){FindKeyPropertyInDataType();}public void Insert(T instance){try{var id = KeyPropertyInfo.GetValue(instance, null);repository[id] = instance;}catch (Exception e){throw new Exception(e.ToString());}}private void FindKeyPropertyInDataType(){foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()){object[] attributes = propertyInfo.GetCustomAttributes(typeof(RepositoryKey), false);if (attributes != null && attributes.Length == 1){KeyPropertyInfo = propertyInfo;}else{throw new Exception("more than one repository key exist");}}}
}

定义DbRepository:用来操作关系型数据库Sqlite

public class DbRepository<T> : IRepository<T> where T : class, new()
{private readonly SQLiteConnection _connection;//...省略部分代码...public void Insert(T instance){try{_connection.Insert(instance);}catch (Exception e){throw new Exception(e.ToString());}}}

定义RestRepository:以WebService的形式访问和持久化远程数据

public class RestRepository<T, R>:IRepository<T> where T : class, new() where R : class, new()
{//...省略部分代码...public void Insert(T instance){//通过WWW像远程发送消息}
}

小结

Repository 模式是很常见的数据层技术,对于.NET 程序员来说就是DAL,而对于Java程序员而言就是DAO。我们扩展了不同的Repository 对象来对不同的介质进行访问和持久化,这也是今后对缓存的实现做准备。
源代码托管在Github上,点击此了解

转载于:https://www.cnblogs.com/OceanEyes/p/thinking_in_repository_pattern.html

相关文章:

PHP连接数据库并创建一个表

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 <html> <body><form action"test.class.php" method"post"> title: <input type"text" name"title"><br> centent: <input t…

MyBatis 入门

什么是 MyBatis &#xff1f; MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手工设置参数以及抽取结果集。MyBatis 使用简单的 XML 或注解来配置和映射基本体&#xff0c;将接口和 Java 的 POJOs(Plain Old Java O…

cms基于nodejs_我如何使基于CMS的网站脱机工作

cms基于nodejsInterested in learning JavaScript? Get my ebook at jshandbook.com有兴趣学习JavaScript吗&#xff1f; 在jshandbook.com上获取我的电子书 This case study explains how I added the capability of working offline to the writesoftware.org website (whic…

how-to-cartoon-ify-an-image-programmatically

http://stackoverflow.com/questions/1357403/how-to-cartoon-ify-an-image-programmatically 转载于:https://www.cnblogs.com/guochen/p/6655333.html

Android Studio 快捷键

2015.02.05补充代码重构快捷键 Alt回车 导入包 自动修正CtrlN 查找类​CtrlShiftN 查找文件CtrlAltL 格式化代码CtrlAltO 优化导入的类和包AltInsert 生成代码(如get,set方法,构造函数等)CtrlE或者AltShiftC 最近更改的代码CtrlR 替换文本CtrlF 查找文本CtrlShiftSpace 自动补全…

【微信小程序】异步请求,权重,自适应宽度并折行,颜色渐变,绝对定位

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 写这篇博文主要是为了能够给到大家做类似功能一些启迪&#xff0c;下面效果图中就是代码实现的效果&#xff0c;其中用到的技巧点还是比较多的&#xff0c; <!--pages/demo_list/d…

服务器部署基础知识_我在生产部署期间学到的知识

服务器部署基础知识by Shruti Tanwar通过Shruti Tanwar 我在生产部署期间学到的知识 (What I learned during production deployment) Production deployment. The final stage of every project. When all the hard work you’ve put in over the course of time goes live t…

STM32 KEIL中 负数绝对值处理

使用数码管显示负温度时需要把负数转换为绝对值 #include<math.h> 使用abs 或者自己写函数 #define ABS(x) ((x)>0?(x):-(x)))转载于:https://www.cnblogs.com/yekongdexingxing/p/6657371.html

js数组按照下标对象的属性排序

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 根据数组中某个参数的值的大小进行升序 <script type"text/javascript">function compare(val) {return function (a, b) {var value1 a[val];var value2 b[val];return value1…

window 下相关命令

1. 启动window服务(各种应用启动设置的地方)命令方式&#xff1a; 1). window 按钮(输入CMD的地方)处输入&#xff1a;services.msc &#xff0c;然后执行。 // 输入命令正确&#xff0c;上面的待选框中会出现要执行的命令。msc 可以理解为Microsoft client 2). 计算机 -- …

javascript语法糖_语法糖和JavaScript糖尿病

javascript语法糖by Ryan Yurkanin瑞安尤卡宁(Ryan Yurkanin) 语法糖和JavaScript糖尿病 (Syntactic Sugar and JavaScript Diabetes) Syntactic sugar is shorthand for communicating a larger thought in a programming language.语法糖是用编程语言传达更大思想的简写。 …

《DSP using MATLAB》示例Example7.23

代码&#xff1a; wp 0.2*pi; ws 0.3*pi; Rp 0.25; As 50; [delta1, delta2] db2delta(Rp, As);[N, f, m, weights] firpmord([wp, ws]/pi, [1, 0], [delta1, delta2]);N f m weightsh firpm(N, f, m, weights); [db, mag, pha, grd, w] freqz_m(h, [1]);delta_w 2*pi…

css画图笔记

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 在网页中&#xff0c;经常会用到各种Icon&#xff0c;如果老是麻烦设计狮画出来不免有些不好意思&#xff0c;所以有时候我们也可以用CSS写出各种简单的形状&#xff0c;一来可以减轻…

Web前端开发最佳实践(8):还没有给CSS样式排序?其实你可以更专业一些

前言 CSS样式排序是指按照一定的规则排列CSS样式属性的定义&#xff0c;排序并不会影响CSS样式的功能和性能&#xff0c;只是让代码看起来更加整洁。CSS代码的逻辑性并不强&#xff0c;一般的开发者写CSS样式也很随意&#xff0c;所以如果不借助工具&#xff0c;不太容易按照既…

超越Android:Kotlin在后端的工作方式

by Adam Arold亚当阿罗德(Adam Arold) 超越Android&#xff1a;Kotlin在后端的工作方式 (Going Beyond Android: how Kotlin works on the Backend) This article is part of a series.本文是系列文章的一部分。 While most developers use Kotlin on Android, it is also a …

词汇的理解 —— 汉译英(术语)

词汇的理解 —— 英译汉 1. 名词 机制&#xff1a;mechanism&#xff0c;系统&#xff1a;system&#xff1b;2. 动词 融资&#xff1a;financing&#xff1b;制动&#xff1a;braking&#xff0c;就是“刹车”&#xff1b;3. 音乐与乐器 horn&#xff1a;喇叭&#xff0c;号角…

Swift从零开始学习_08(代理协议传值)

Swift中的代理协议的写法. 这是第一个页面有一个button和一个label, button点击跳到下一个页面. 第二个页面有一个输入框和一个按钮, 点击按钮把输入框里的内容设置为第一个页面label的内容.效果如下 接下来是代码部分.跟OC的写法还是一样的.这里不再写第一个页面的那些UI的…

[微信小程序]商城之购买商品数量实现

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 这里有三种变更数量的方式&#xff0c; 加号&#xff0c;减号&#xff0c;input输入 &#xff0c; 这里做了限制&#xff0c;数量不能小于等于0并且不能超过现有库存&#xff0c;下面是…

测试nginx网站代码_在40行以下代码中使用NGINX进行A / B测试

测试nginx网站代码by Nitish Phanse由Nitish Phanse 在40行以下代码中使用NGINX进行A / B测试 (A/B testing with NGINX in under 40 lines of code) A/B Testing, has enabled designers and product managers to get a deep insight into user behavioral patterns.A / B测试…

HttpServletResponse,HttpServletRequest详解

HttpServletResponse,HttpServletRequest详解 1、相关的接口 HttpServletRequest HttpServletRequest接口最常用的方法就是获得请求中的参数&#xff0c;这些参数一般是客户端表单中的数据。同时&#xff0c;HttpServletRequest接口可以获取由客户端传送的名称&#xff0c;也可…

[微信小程序]this.setData , that.setData , this.data.val三者之间的区别和作用

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 1.this.setData({ }) <view bindtouchmove"tap_drag" bindtouchend"tap_end" bindtouchstart"tap_start" class"page-top" style"{…

jQuery(一)引入

一、jQuery简介 jQuery是一个兼容多浏览器的javascript库&#xff0c;核心理念是write less,do more(写得更少,做得更多) 二、安装 2.1、下载 下载地址&#xff1a;http://jquery.com/download/ 2.2、引入 在页面头部加入 <head> <meta http-equiv"Content-Type&…

javascript 堆栈_JavaScript调用堆栈-它是什么以及为什么它是必需的

javascript 堆栈The JavaScript engine (which is found in a hosting environment like the browser), is a single-threaded interpreter comprising of a heap and a single call stack. The browser provides web APIs like the DOM, AJAX, and Timers.JavaScript引擎(可在…

idea崩溃导致的svn插件丢失问题, maven dependencies视图丢失问题

Idea丢失Svn解决办法今天打开Idea&#xff0c;习惯用ctrlt来更新svn&#xff0c;杯具出现了&#xff0c;快捷键失效了&#xff0c;我觉得可能是其他的什么软件占用了这个快捷键&#xff0c;于是重启了一下&#xff0c;发现还是不行&#xff0c;svn信息怎么没了&#xff0c;chan…

python3代码

import urllib.request url"http://mm.taobao.com/json/request_top_list.htm?type0&page1" upurllib.request.urlopen(url)#打开目标页面&#xff0c;存入变量up contup.read()#从up中读入该HTML文件 key1<a href"http#设置关键字1key2"target&qu…

【微信小程序】侧滑栏,手动侧滑出个人中心(完整代码附效果图)

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; 博文分三部分&#xff0c;1.效果图及功能效果说明 2.实现思路 3.源代码 欢迎加入微信小程序开发交流群&#xff08;173683895&#xff09; 一.老惯例先上效果图&#xff0c;本篇博…

1:1 人脸比对 开源_Hacktoberfest:我的开源门户

1:1 人脸比对 开源by Maribel Duran通过Maribel Duran Hacktoberfest&#xff1a;我的开源门户 (Hacktoberfest: My Gateway to Open Source) “Individually, we are one drop. Together, we are an ocean.”“就个人而言&#xff0c;我们只是一滴滴。 在一起&#xff0c;我们…

地图收敛心得170405

寻路算法大总结! 交换机生成树采用的是完全不同的D-V(distance vector)距离矢量算法,并不是很可靠. 并不是任意两点之间的最短路径,因为任意两点之间取最短路径可能有环路:总权更大 交换机STP不一定是最小生成树!!!举例论证 因为它只是所有交换机到根桥最短 贪心算法的味道 kru…

微信小程序游戏开发文档以及开发工具地址

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; 微信官方于 2017 - 12 - 28 日 开发微信小程序 开发小游戏 &#xff0c; 微信小程序小游戏开发官方文档的地址 https://mp.weixin.qq.com/debug/wxagame/dev/index.html?t20171228…

c#编译执行过程

创建一个简单的控制台程序&#xff0c;源码如下&#xff1a; using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace csharpBuildProcess {class Program{static void Main(string[] args){for (int i 0; i < 100; i){if(i%20)…