emptysoul

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  25 Posts :: 0 Stories :: 23 Comments :: 0 Trackbacks

常用链接

留言簿(18)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

原型模式(Prototype)解决的目标是通过一个已有的对象来创建一个新对象。
比如在使用Ghost对系统进行备份时,实际上备份的是操作系统的一个副本,而不是一个全新的操作系统,这时操作系统就是原型对象,UML图如下:


实现代码:
//OS.h
class OS
{
public:
    
virtual ~OS();

    
virtual OS* Clone() const = 0;
protected:
    OS();
};

//OS.cpp
#include "stdafx.h"
#include 
"OS.h"

OS::OS()
{

}

OS::
~OS()
{

}

//Windows9x.h
#include "OS.h"

class Windows9x : public OS
{
public:
    Windows9x();
    Windows9x(
const Windows9x&);
    
virtual ~Windows9x();

    OS
* Clone() const;
};

//Windows9x.cpp
#include "stdafx.h"
#include 
"Windows9x.h"
#include 
<iostream>

using namespace std;

Windows9x::Windows9x()
{
    cout 
<< "创建Windows9x" << endl;
}

Windows9x::Windows9x(
const Windows9x& win)
{
    cout 
<< "克隆Windows9x" << endl;
}

Windows9x::
~Windows9x()
{

}

OS
* Windows9x::Clone() const
{
    
return new Windows9x(*this);
}

//WindowsXP.h
#include "OS.h"

class WindowsXP : public OS
{
public:
    WindowsXP();
    WindowsXP(
const WindowsXP&);
    
virtual ~WindowsXP();

    OS
* Clone() const;
};

//WindowsXP.cpp
#include "stdafx.h"
#include 
"WindowsXP.h"
#include 
<iostream>

using namespace std;

WindowsXP::WindowsXP()
{
    cout 
<< "创建WindowsXP" << endl;
}

WindowsXP::WindowsXP(
const WindowsXP& win)
{
    cout 
<< "克隆WindowsXP" << endl;
}

WindowsXP::
~WindowsXP()
{

}

OS
* WindowsXP::Clone() const
{
    
return new WindowsXP(*this);
}

//main.cpp
#include "stdafx.h"
#include 
"OS.h"
#include 
"Windows9x.h"
#include 
"WindowsXP.h"

int main(int argc, char* argv[])
{
    OS
* pOS = new Windows9x;
    pOS
->Clone();
    delete pOS;
    pOS 
= new WindowsXP;
    pOS
->Clone();
    delete pOS;
    
return 0;
}

最后输出为:
创建Windows9x
克隆Windows9x
创建WindowsXP
克隆WindowsXP
posted on 2009-02-09 15:52 emptysoul 阅读(820) 评论(1)  编辑 收藏 引用

Feedback

# re: 设计模式-原型模式 2010-08-23 14:17 w8u
这样有意思么?
对于main来说,为什么要这么复杂呢?
既然他都能new windows9x,windowsXP了,还搞什么clone呢?何必这么麻烦?

另外,clone似乎有new动作,没有对应的delete。
  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理