大话设计模式模板方法模式c++实现

模板方法模式

其他二十三种设计模式

#include<iostream>

using namespace std;

//模板方法模式
//模板类
class TestPaper{
    
    
public:
	void TestQuestion1() {
    
    
		cout << "问题1: **" << endl;
		cout << "答案: " << Answer1() << endl;
	}
	void TestQuestion2() {
    
    
		cout << "问题2: **" << endl;
		cout << "答案: " << Answer2() << endl;

	}
	void TestQuestion3() {
    
    
		cout << "问题3: **" << endl;
		cout << "答案: " << Answer3() << endl;
	}
	void Make() {
    
    
		TestQuestion1();
		TestQuestion2();
		TestQuestion3();
	}

protected:
	virtual string Answer1() {
    
    
		return "";
	}
	virtual string Answer2() {
    
    
		return "";
	}
	virtual string Answer3() {
    
    
		return "";
	}
};

class TestPaperA :public TestPaper {
    
    
protected:
	virtual string Answer1() {
    
    
		return "b";
	}
	virtual string Answer2() {
    
    
		return "c";
	}
	virtual string Answer3() {
    
    
		return "a";
	}
};

class TestPaperB :public TestPaper {
    
    
protected:
	virtual string Answer1() {
    
    
		return "c";
	}
	virtual string Answer2() {
    
    
		return "a";
	}
	virtual string Answer3() {
    
    
		return "a";
	}
};

void test1() {
    
    
	cout << "A试卷: " << endl;
	TestPaper* studentA = new TestPaperA();
	studentA->Make();

	cout << "B试卷: " << endl;
	TestPaper* studentB = new TestPaperB();
	studentB->Make();

	delete studentB;
	delete studentA;
}

int main() {
    
    
	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114163102