哪个更好:全局字符串或单例? [英] What is better: Global string or singleton?
问题描述
对于我的全新ORM( chibi-ORM ),我面临一个设计决策.
For my brand new ORM (chibi-ORM) I face a design decision.
我正在建立关系的API,例如:
I'm building the API for relationships, like:
@interface SamplePerson : DbObject {
NSString *name;
DbObjectRelation *cities;
}
现在,对于 DbObjectRelation
,我有这个模型:
Now, for DbObjectRelation
I have this mockup:
@interface DbObjectRelation : NSObject {
NSMutableArray *childRows;
DbObject *parent;
BOOL isLoaded;
}
-(void) load;
-(void) addObject:(DbObject *) childRow;
-(void) removeObject:(DbObject *) childRow;
- (id)initWitParent:(DbObject *)parentObject;
因此,我需要一种内部加载方式来知道哪个数据库用于加载记录.
So, I need a way inside load of know which database use for load the records.
我认为数据库连接中包含以下内容:
I think in have in my DB connection something like:
static NSString *currentDbNameSingleton = nil;
+(NSString *)currentDbName {
@synchronize( self ) {
if ( currentDbNameSingleton == nil ) {
currentDbNameSingleton = [[NSString alloc]
}
}
return sharedInst;
}
+(void) setCurrentDbName(NSString *)name {
@synchronize( self ) {
currentDbNameSingleton = [name copy];
}
}
但是想知道是否最好将DB类构建为单例.这是用于iPhone项目...
But wonder if is better build the DB class as a singleton. This is for iPhone projects...
推荐答案
像当前正在使用的那样,在静态变量周围使用一组类访问器/变量是很合理的.如果不打算更改数据库名称,另一种非常常见的解决方案是将其与单独的文件(例如Constants.h)以及其他常量字符串(例如字典和用户默认键)一起放置在一个文件中.
Using a set of class accessors/mutators around a static variable like you're currently doing is pretty reasonable. Another pretty common solution if you're not going to change the database name would be to put it in a separate file, say Constants.h, along with other constant strings like dictionary and user defaults keys.
如果您有与数据库相关的其他代码可以重构到一个地方,那么为数据库内容构建单例类是一个很好的方法.我不会创建仅用于容纳字符串的类.
If you have additional code related to your database that you can refactor into a single place, then that's a pretty good point to built a singleton class for your database stuff. I wouldn't create a class just to hold a string though.
这篇关于哪个更好:全局字符串或单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!