#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