《大话设计模式》简单工厂模式的实现,用VS2010的MFC实现程序。
客户端界面如下:
客户端的实现如下:
1 void CFactoryDesignDemoDlg::OnBnClickedOk() 2 { 3 // TODO: 在此添加控件通知处理程序代码 4 UpdateData(true); 5 //一般LP代表指针,C代表const,T代表宽字符,STR代表字符串,这么对应下来大概是这样: 6 //LPCTSTR = const TCHAR* 7 8 Operation* opt = OperationFactory::createOperation(m_opt); 9 opt->setNumberAB(m_editA,m_editB); 10 try{ 11 m_editResult = opt->getResult(); 12 }catch(...){ 13 AfxMessageBox(_T("Cannot divide into 0")); 14 } 15 UpdateData(false); 16 17 //CDialogEx::OnOK(); 18 }
下面是OptClasses.h源代码
1 class Operation{ 2 3 private: 4 double _numA; 5 double _numB; 6 7 public: 8 double getNumberA(){return _numA;}; 9 double getNumberB(){return _numB;}; 10 void setNumberA(double numA){_numA = numA;} 11 void setNumberB(double numB){_numB = numB;} 12 void setNumberAB(double numA,double numB); 13 virtual double getResult(){return 0.0;}; 14 }; 15 16 class OperationAdd : public Operation{ 17 public: 18 double getResult(){ 19 return getNumberA()+getNumberB(); 20 } 21 }; 22 23 class OperationSub : public Operation{ 24 public: 25 double getResult(){ 26 return getNumberA()-getNumberB(); 27 } 28 }; 29 30 class OperationMul : public Operation{ 31 public: 32 double getResult(){ 33 return getNumberA()*getNumberB(); 34 } 35 }; 36 37 class OperationDiv : public Operation{ 38 public: 39 double getResult(); 40 }; 41 42 class OperationFactory{ 43 public: 44 static Operation* createOperation(CString opt); 45 };
下面是OptClasses.cpp的源代码:
1 #include "stdafx.h" 2 #include "OptClasses.h" 3 4 void Operation::setNumberAB(double numA, double numB){ 5 _numA = numA; 6 _numB = numB; 7 } 8 9 double OperationDiv::getResult(){ 10 if(getNumberB()==0){ 11 throw 0; 12 }else{ 13 return getNumberA()/getNumberB(); 14 } 15 } 16 17 Operation* OperationFactory::createOperation(CString optString){ 18 char* opt = (char*)(LPCTSTR)optString; 19 Operation* oper = NULL; 20 switch(*opt){ 21 case ‘+‘: 22 oper = new OperationAdd(); 23 break; 24 case ‘-‘: 25 oper = new OperationSub(); 26 break; 27 case ‘*‘: 28 oper = new OperationMul(); 29 break; 30 case ‘/‘: 31 oper = new OperationDiv(); 32 break; 33 } 34 return oper; 35 }
学习笔记:
1、最开始接触JAVA时,不明白为什么要业务逻辑和界面逻辑分开,阅读代码时从不同类之间转来转去,原因是希望软件具有更好的可移植性,使程序更加灵活、容易修改、易于复用。
2、活字印刷术之所以成为四大发明之一,虽然不是从零到有的发明,但是大大的提高了生产力,可改字(可维护)、重复使用(可复用)、可加字(可扩展)、可排版(灵活性好),具有面向对象的特点。
时间: 2024-10-18 09:37:01