Design Mode 7: Template Method Mode

Source: Internet
Author: User

1. My description

The template method mode is to move the unchanged behavior to the superclass, remove the repeated code in the subclass to reflect its advantages, and provide good code reuse.

My understanding is like when we learned to draw pictures, the teacher said that everyone is better than this apple, and then draw a picture of their own, and then everyone is there to draw, however, what we draw is different, but what we share is that we compare the pattern with the same apple.

For another example, a gets 90 points for the same exam and B gets 80 points for the same exam. This test is the same: A and B have the same exam, but they have different scores because they have different answers. In the template method mode, the exam questions remain unchanged. We will move them to the super class. The difference is our answer in this exam.

Ii. UML diagram

  

For my above example, my UML diagram should be:

  

Iii. Implementation of my exam template code

#include<iostream>using namespace std;class Test {public:    void Question() {        cout << "Question1 : who is Feng‘jie?" << endl;    }    virtual void Answer() {}};class Answer1 : public Test {public:    virtual void Answer() {        cout << "Answer1‘s answer: " << "C" << endl;    }};class Answer2 : public Test {public:    virtual void Answer() {        cout << "Answer2‘s answer: " << "B" << endl;    }};int main() {    Test *p_test1 = new Answer1();    p_test1->Question();    p_test1->Answer();    delete p_test1;    Test *p_test2 = new Answer2();    p_test2->Question();    p_test2->Answer();    delete p_test2;        return 0;}

 

  

Design Mode 7: Template Method Mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.