您的位置:首页 > 其它

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

2013-08-05 11:11 239 查看
原型模式取代 基类的静态函数违背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);

}

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

再附一文章,是: 虚拟拷贝技术 (这里的虚拷贝函数采用的技术依然是原型模式)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: