[编辑]将标题从“JS:用于收集或单个项目的异性二传手/吸气器?JS:动态对象交叉引用池
关于编写混合getter/setter的能力的一些问题...对于我的国际象棋应用程序,我有一个比树更类似于图的对象图。所以我决定把数据结构中的各种对象集中在一起,这些数据结构既包含对象物体又包含对象之间的关系。
喜欢的东西:
// in js/app/base/pools.js
var Pool = function() {
this.items = {};
this.relations = {};
};
/**
* store an object into the pool
* and augment it with relation/pooling capabilities
* @param string key
* @param Object obj
*/
Pool.prototype.store = function(key, obj) {
var self = this;
Object.defineProperty(obj.constructor.prototype, "pool", {
set : undefined,
get : function() {
return self;
}
});
this.items[key] = obj;
};
/**
* looks for an object in the pool
* @param string
*/
Pool.prototype.find = function(key) {
return this.items[key];
};
关系被存储为成对[OBJ1,OBJ2]在池实例的 “关系” 属性 。我基本上有两种关系:
一到一个:一元corespondances像棋子< --->位置,或接口实现像棋子< --->典当| ... |王
一个一对多像板[X1] < ---> [64]瓷砖
这些关系的目的(由池的方式)是双向的,并且必须设置原子(例如交易),因为对象交叉引用需要是“ACID”,对于上面的例子,1板包含64块瓷砖,并且每块瓷砖知道它的站立板。
对于1:1的关系,也许没有问题,因为我可以设置:
chessman.location = location;
// AND AT THE SAME TIME :
location.chessman = chessman;
// with two Object.defineProperty(...) combined
麻烦配备了1-N关系,因为我能写:
// 1st : defining relation
// ... (see below)
// 2nd setting a relation
board1.tiles.add(tile_63);
// and
tile_63.board = board1;
// 3rd getting values
board1.tiles --> a collection of tiles (array)
tile_63.board --> board1 object
在关系由传递参数对象给予池实例的主程序:
pool.defineRelation("board-contains-tiles", {
tiles : { subject : boards.Board, multiple : true },
board : { subject : tiles.Tile, multiple : false }
});
来定义关系,1面是一个普通的getter/setter,但是N面更像是一个吸气剂加法器,因为我们必须填充(板上有瓷砖)...所以这是行不通的:
Pool.prototype.defineRelation = function(alias, definition) {
this.relations[alias] = [];
var self = this, linker;
var relation = self.relations[alias];
var subject, multiple;
// iterate through relation short names
for(name in definition) {
subject = definition[name].subject;
multiple = definition[name].multiple;
console.log("loop with name : " + name + " subject is : " + subject);
var getter = function() {
var result = [];
for(r = 0; r < relation.length; r++) {
// [x,y] storing
if(relation[r][0] == this)
result.push(relation[r][1]);
// [y,x] storing
if(relation[r][1] == this)
result.push(relation[r][0]);
return result;
};
var setter;
if(multiple) {
setter = function() {};
setter.add = function(x) { relation.push([this, x]); };
} else {
setter = function(x) { relation.push([this, x]); };
}
Object.defineProperty(subject.prototype, name, {
set : setter,
get : getter
});
}
};
问题: 我认为有可能这样做,但怎么做?或者更好的方式,像Delphi的TComponent,或者像DOM树一样?
也可参见: 老,丑陋和杂乱的代码库可以在我的网站上找到:
www.eozine.fr --> Jet d'echecs --> ColorChess
,如果你婉吨至看到以前的结果(2009)
问候。
一种可能的方法来解决:养殖对象(类对象)http://gameprogrammingpatterns.com/type-object.html –
它SA欺骗......我希望这是一个可解决的问题... –