Big talk design mode--first chapter: Simple Factory mode

Source: Internet
Author: User

#include <iostream> #include <string> #include <exception>//c++ Library using namespace for standard exception types Std;bad_ Exception somethingwrong;//in C + + The default inheritance of class is private and struct default inheritance is public//static class static member function, that is, object-independent. The value in a class is not changed by instantiating an object. Class operation//operation Class (base class) {public:double numbera; double numberb;virtual Double GetResult ()// The virtual function GetResult to get the result of the calculation. {Double Result=0;return result;}};/ /subtraction class, inheriting from the algorithm class (each subclass of the Operation Class) class Operationadd:public operation{public:double GetResult () {return numbera+numberb;}}; Class Operationsub:public operation{public:double GetResult () {return numberb-numbera;}}; Class Operationmul:public operation{public:double GetResult () {return numbera*numberb;}}; Class Operationdiv:public operation{public:double GetResult () {if (numberb==0) throw Somethingwrong;return numberA/ numberb;}};/ /Arithmetic factory class operationfactory{public:static operation* CreateOperation (char operate) {switch (operate) {case ' + ': return New Operationadd;break;case '-': return new operationsub;break;case ' * ': return new Operationmul;break; case '/': return new Operationdiv;break;}}; int main () {//client program Operation *a;a=operationfactory::createoperation ('/'); a->numbera=8;a->numberb=0;try{ Cout<<a->getresult () <<endl;} catch (Bad_exception &) {cerr<< "B should not be 0"; Cout<<endl;} System ("pause"); return 1;}

  

Big talk design mode--first chapter: Simple Factory 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.