您的位置:首页 > 移动开发 > Objective-C

条款18: 让接口容易被正确使用,不易被误用

2010-02-09 23:17 381 查看
1、好的接口很容易被正确使用,不容易被误用.你应该在你的所有接口中努力达成这些性质.
2、"促进正确使用"的办法包括接口的一致性,以及与内置类型的行为兼容.
问题代码:

class Date{
public:
Date(int month,int day,int year);
...
};


修改:

struct Day{
explicit Day(int dayValue):value_(dayValue){}
int value_;
};
struct Month{
explicit Month(int monthValue):value_(monthValue){}
int value_;
};
struct Year{
explicit Year(int yearValue):value_(yearValue){}
int value_;
};

class Date{
public:
Date(const Month& m,const Day& d,const Year& y);
...
};


进一步修改:

class Month{
public:
static Month Jan(){return Month(1);}
static Month Feb(){return Month(2);}
...
static Month Dec(){return Month(12);}
...
private:
explicit Month(int m); //prvent create object from outward
...
};

Date d(Month::Mar(),Day(30),Year(1995));


3、"阻止误用"的办法包括建立新类型、限制类型上的操作、束缚对象值以及消除客户的资源管理责任.
4、tr1::shared_ptr支持定制型删除器.这可防范DLL问题,可被用来自动解除互斥锁等等.

std::tr1::shared_ptr<Investment> createInvestment(){
std::tr1::shared_ptr<Investment> retVal=(static_cast<Investment*>(0),getRidOfInvestment);
...
retVal=...;//让retval指向正确的对象
return retVal;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  date struct class object dll