原型模式(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