Construct Named Parameter Idiom

 Sometimes, construct  a object has many option parameter.
 The traditional solution is to write a construct using many parameters and set paramter which may be changed most possible at first and set the default values for each parameters.

     class  File
    
{
    
public:
        File(std::
string filename_ = "",  
            
bool readOnly_ = false,
            
bool createIfNotExist = false
            
int blockSize_ = 4096
            
//, ... and others
            )
        
{
            ...
        }

    }

 all of this will be OK, if you just create File using the default arguements value.

 File myFile("Filename.ext");

 but if you just want to changed blockSize, then you have to write:
 File myFile("Filename.ext", false, false, 8192);

 Then is there a better way to operate such construction, The answer is yes and it called: "Named Parameter Idiom"

 see the new File class, first abstract the datas of the construct parameters to a class OpenFile:

 


class  File;
class  OpenFile  {
    
public:
        OpenFile(
const std::string& filename);
        
// sets all the default values for each data member
        OpenFile& readonly(); // changes readonly_ to true
        OpenFile& readwrite(); // changes readonly_ to false
        OpenFile& createIfNotExist();
        OpenFile
& blockSize(unsigned nbytes);
        ...
    
private:
        friend 
class File;
        std::
string filename_;
        
bool readonly_; // defaults to false [for example]
        bool createIfNotExist_; // defaults to false [for example]
        ...
        unsigned blockSize_; 
// defaults to 4096 [for example]
        ...
    }
;

    inline OpenFile::OpenFile(
const  std:: string &  filename)
        : filename_ (filename)
        , readonly_ (
false )
        , createIfNotExist_ (
false )
        , blockSize_ (
4096u )
    
{
    }
;

    inline OpenFile
&  OpenFile:: readonly ()
    
{ readonly_ = truereturn *this; }
    inline OpenFile
&  OpenFile::readwrite()
    
{ readonly_ = falsereturn *this; }
    inline OpenFile
&  OpenFile::createIfNotExist()
    
{ createIfNotExist_ = truereturn *this; }
    inline OpenFile
&  OpenFile::blockSize(unsigned nbytes)
    
{ blockSize_ = nbytes; return *this; }
}

And the file class is :

 

     class  File {
        
public :
        File(
const  OpenFile &   params );
        ...
    };

    File::File(
const  OpenFile &   params )
    {
        ...
    }

And using File will be simple:

using default parameters value, just:

File f  =  OpenFile( " foo.txt " );

If you wanted just changing blockSize:

File f  =  OpenFile( " foo.txt " ).blockSize( 1024 );

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值