C++实现Builder设计模式

------------------------------ 以下为.h文件 --------------------------------------------

#pragma once

#include <iostream>

using namespace std;

class Student
{
public:
Student();
~Student();

string getName();
void setName(string name);
int getAge();
void setAge(int age);
int getType();
void setType(int type);

Student(Student* stu){
name = stu->name;
age = stu->age;
type = stu->type;
};

static class StudentBuilder{
public:
StudentBuilder(){
}

StudentBuilder createStudent(){
student = new Student();
return *this;
};

StudentBuilder name(string name){
student->name = name;
return *this;
};

StudentBuilder age(int age){
student->age = age;
return *this;
};


StudentBuilder type(int type){
student->type = type;
return *this;
};

Student build()
{
return this->student;
}

private:
Student* student;
};


private:
string name;
int age;
int type;

};

------------------------------ 以下为.cpp文件 --------------------------------------------

#include "stdafx.h"
#include "Student.h"


Student::Student()
{
}


Student::~Student()
{
}


string Student::getName(){
return this->name;
}
void Student::setName(string name){
this->name = name;
}
int Student::getAge(){
return this->age;
}
void Student::setAge(int age){
this->age = age;
}
int Student::getType(){
return this->type;
}
void Student::setType(int type){
this->type = type;
}

------------------------------ 以下调用 --------------------------------------------

#include "stdafx.h"
#include "Student.h"
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
Student::StudentBuilder buide ;
Student stu1 = buide.createStudent().age(14).name("dfas").type(2).build();

Student stu2 = buide.age(13).name("zhangsan").build();

printf("%d \n", stu1.getAge());
printf("%s \n", stu1.getName().c_str());

printf("%d \n", stu2.getAge());
printf("%s \n", stu2.getName().c_str());

system("pause");

return 0;
}

猜你喜欢

转载自www.cnblogs.com/tianhu9102/p/10140113.html