zoukankan      html  css  js  c++  java
  • 1 简单工厂模式

     工厂模式

    代码
    1 template<class T>
    2  class Operation
    3 {
    4 public:
    5 Operation()
    6 {
    7 numberA = 0;
    8 numberB = 0;
    9 }
    10 virtual T GetResult()
    11 {
    12 T result = 0;
    13 return result;
    14 }
    15 public:
    16 T numberA;
    17 T numberB;
    18 };
    19
    20 template<class T>
    21 class OperationAdd : public Operation<T>
    22 {
    23 public:
    24 T GetResult()
    25 {
    26 return numberA + numberB;
    27 }
    28 };
    29
    30 template<class T>
    31 class OperationMinus : public Operation<T>
    32 {
    33 public:
    34 T GetResult()
    35 {
    36 return numberA - numberB;
    37 }
    38 };
    39
    40 template<class T>
    41 class OperationMultiply : public Operation<T>
    42 {
    43 public:
    44 T GetResult()
    45 {
    46 return numberA * numberB;
    47 }
    48 };
    49
    50 template<class T>
    51 class OperationDivide : public Operation<T>
    52 {
    53 public:
    54 T GetResult()
    55 {
    56 return numberA / numberB;
    57 }
    58 };
    59
    60 //工厂类
    61 //到底要实例化谁,将来会不会增加实例化的对象,比如增加开跟运算,这是很容易变化的地方,
    62 //应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂
    63 template<class T>
    64 class OperationFactory
    65 {
    66 public:
    67 static Operation<T>* CreateOperate(string operate) //根据客户需要,返回一个产品
    68 {
    69 Operation<T>* oper = NULL;
    70 if(operate == "+")
    71 {
    72 oper = new OperationAdd<T>();
    73 }
    74 else if(operate == "-")
    75 {
    76 oper = new OperationMinus<T>();
    77 }
    78 else if(operate == "*")
    79 {
    80 oper = new OperationMultiply<T>();
    81 }
    82 else if(operate == "/")
    83 {
    84 oper = new OperationDivide<T>();
    85 }
    86 else //默认产生的是加法运算
    87 {
    88 oper = new OperationAdd<T>();
    89 }
    90
    91 return oper;
    92
    93 }
    94 };
    95
    96 //客户端代码
    97 int main()
    98 {
    99 Operation<int>* oper = OperationFactory<int>::CreateOperate("+");
    100 oper->numberA = 100;
    101 oper->numberB = 200;
    102 double result = oper->GetResult();
    103 cout<<result<<endl;
    104 return 0;
    105 }
  • 相关阅读:
    Robot Framework (二)---测试数据
    Robot Framework(一)---Robot Framework 简介
    软件测试---产品需求文档测试
    浅谈Python 中的闭包
    浅析 Python中__init__.py
    PEP8---Python命名规则
    软件产品测试经验(一)---产品专项测试
    Microsoft Office Excel 不能访问文件。。。 可能的原因有。。。
    记HttpListener调用exe程序界面无法打开
    简单搞懂逆变与协变
  • 原文地址:https://www.cnblogs.com/sifenkesi/p/1719618.html
Copyright © 2011-2022 走看看