原型模式替代基类的静态函数违背ocr原则去dynamic_cast分支而拷贝对象的法子

原型模式取代 基类的静态函数违背ocr原则去dynamic_cast分支拷贝对象


假设这么一个需求, 有一个容器要存储很多类的指针;容器可以拷贝。  


见过一个人写的代码:


基类采用了静态函数来完成 派生类的克隆。


伪代码如下:


//Sample.h


class Derived1;
class Derived2;


class Sample
{
protected:
enum eType{ type1 ,type2 };
int m_nType;
protected:
Sample(void);
virtual ~Sample(void);
Sample(const Sample& rhs);
Sample& operator = (const Sample& rhs);
protected:
virtual int GetType() const =0 ;
public:
static Sample* Clone(Sample const& rhs);
};




class Derived1: public Sample
{
public:
Derived1():Sample()
{
m_nType = type1;
}
public:
virtual int GetType() const
{
return m_nType;
}
};




class Derived2: public Sample
{
public:
Derived2():Sample()
{
m_nType = type2;
}
private:
virtual int GetType() const
{
return m_nType;
}
};






//Sample.cpp
Sample::Sample(void)
{
}


Sample::~Sample(void)
{
}


Sample* Sample::Clone( const Sample& rhs )
{
Sample  const * prhs = & rhs;
Sample * phrs2 = const_cast< Sample* > (prhs);
if( phrs2 == NULL)
return NULL;
switch( prhs->GetType() )
{
case type1:
{
Derived1* pD1 = NULL;
pD1 = dynamic_cast<Derived1*> (phrs2);
return pD1;
}
break;
case type2:
{
Derived2* pD1 = NULL;
pD1 = dynamic_cast<Derived2*> (phrs2);
return pD1;
}
default:
return NULL;
}
}



违背ocr原则, 显得别扭。 因为static函数没有指针,所以只能够通过参数传进来一个待拷贝的对象.




这个问题用原型模式解决.
//Sample.h 
class Derived1;
class Derived2;


class Sample
{
protected:
enum eType{ type1 ,type2 };
int m_nType;
protected:
Sample(void);
virtual ~Sample(void);
Sample(const Sample& rhs);
Sample& operator = (const Sample& rhs);
public:
virtual int GetType() const = 0;
virtual Sample* Clone( ) const = 0 ; //新版本
};




class Derived1: public Sample
{
public:
Derived1():Sample()
{
m_nType = type1;
}
Derived1& operator = (const Derived1& rhs);
public:
inline virtual int GetType() const
{
return m_nType;
}
virtual Sample* Clone( ) const ;
};




class Derived2: public Sample
{
public:
Derived2():Sample()
{
m_nType = type2;
}
Derived1& operator = (const Derived1& rhs);
public:
inline virtual int GetType() const
{
return m_nType;
}
virtual Sample* Clone( ) const ;
};




//Sample.cpp


Sample::Sample(void)
{
}


Sample::~Sample(void)
{
}


Sample::Sample(const Sample& rhs)
{


}


Sample* Derived1::Clone( ) const  //新版本
{
return new Derived1(*this);
}


Sample* Derived2::Clone( ) const  //新版本
{
return new Derived2(*this);

}



原型模式好的文章:原型模式


再附一文章,是: 虚拟拷贝技术 (这里的虚拷贝函数采用的技术依然是原型模式)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值