原型模式 c++版


抽象原型 Prototype.h  &  Prototype.cppios


//
//  Prototype.h
//  Prototype
//
//  Created by hejinlai on 13-8-9.
//  Copyright (c) 2013年 yunzhisheng. All rights reserved.
//
#ifndef __Prototype__Prototype__
#define __Prototype__Prototype__
#include <iostream>
using namespace std;
class Prototype {
                                   
public:
                                   
    Prototype();
    virtual ~Prototype();
                                   
    virtual Prototype * clone() = 0;
                                   
    string getName();
    void setName(string name);
                                   
protected:
                                   
    string name;
};
#endif /* defined(__Prototype__Prototype__) */


//
//  Prototype.cpp
//  Prototype
//
//  Created by hejinlai on 13-8-9.
//  Copyright (c) 2013年 yunzhisheng. All rights reserved.
//
#include "Prototype.h"
Prototype::Prototype()
{
                                
}
Prototype::~Prototype()
{
                                
}
string Prototype::getName()
{
    return name;
}
void Prototype::setName(string name)
{
    this->name = name;
}


具體原型 ConcretePrototype.h  &  ConcretePrototype.cppide


//
//  ConcretePrototype.h
//  Prototype
//
//  Created by hejinlai on 13-8-9.
//  Copyright (c) 2013年 yunzhisheng. All rights reserved.
//
#ifndef __Prototype__ConcretePrototype__
#define __Prototype__ConcretePrototype__
#include <iostream>
#include "Prototype.h"
using namespace std;
class ConcretePrototype : public Prototype{
                    
public:
                    
    ConcretePrototype();
    ConcretePrototype(const ConcretePrototype & p);
    ~ConcretePrototype();
                    
    virtual Prototype * clone();
                    
};
#endif /* defined(__Prototype__ConcretePrototype__) */


//
//  ConcretePrototype.cpp
//  Prototype
//
//  Created by hejinlai on 13-8-9.
//  Copyright (c) 2013年 yunzhisheng. All rights reserved.
//
#include "ConcretePrototype.h"
ConcretePrototype::ConcretePrototype()
{
                 
}
ConcretePrototype::~ConcretePrototype()
{
                 
}
ConcretePrototype::ConcretePrototype(const ConcretePrototype & p)
{
    this->name = p.name;
}
Prototype * ConcretePrototype::clone()
{
    return new ConcretePrototype(*this);
}


測試 main.cpp測試


//
//  main.cpp
//  Prototype
//
//  Created by hejinlai on 13-8-9.
//  Copyright (c) 2013年 yunzhisheng. All rights reserved.
//
#include <iostream>
#include "ConcretePrototype.h"
int main(int argc, const char * argv[])
{
    Prototype *p = new ConcretePrototype();
    p->setName("zhangsan");
    cout << p->getName() << endl;
            
    Prototype *p2 = p->clone();
    cout << p2->getName() << endl;
            
    delete p;
    delete p2;
            
    return 0;
}



測試結果:this


zhangsanspa

zhangsanget

相關文章
相關標籤/搜索