Chain of responsibility (C ++ implementation)

Source: Internet
Author: User

// Chain of responsibility. cpp: defines the entry point of the console application.
//

# Include "stdafx. H"
# Include <iostream>

Using namespace STD;
Typedef int topic;

Class Handler
{
Public:
Handler (handler * h = 0, topic t =-1): successor (H), topic (t)
{
}

Virtual ~ Handler ()
{
}

Virtual void handlerequest (topic t) = 0;
 
 
Protected:
Handler * successor;
Topic topic;
};

//////////////////////////////////////// //////////////

Class concretehandler: Public Handler
{
Public:
Concretehandler (handler * h = 0, topic t =-1): handler (h, T)
{
}
Virtual ~ Concretehandler (){}

Virtual void handlerequest (topic T)
{
If (t = topic)
{
Cout <"done this request:" <t <Endl;
Return;
}
Else
{
If (null! = Successor)
{
Cout <"throw to successor" <Endl;
Successor-> handlerequest (t );

}
}

}
 
};

Int _ tmain (INT argc, _ tchar * argv [])
{
Handler * P1 = new concretehandler (0, 3 );
Handler * P2 = new concretehandler (P1, 2 );
Handler * P3 = new concretehandler (P2, 3 );

Handler * PX = new concretehandler (P3 );
// The PX request topic is 2.
PX-> handlerequest (2 );

Delete P1;
Delete P2;
Delete P3;
Delete PX;
 
Return 0;
}

 

Related Article

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.