思想
继承,多态,封装 封装:将业务逻辑与界面逻辑分开,让它们之间的耦合度下降 继承:不同的运算继承运算类,使得拓展简单安全 多态:通过多态,返回父类的方法实现了计算器的结果 工厂:到底要实例化谁,用一个单独的类来做这个创造实例,工厂会实例化出合适的对象
C++
#include<iostream>
#include<string>
using namespace std;
class Operation {
public:
double double_numberA;
double double_numberB;
public:
virtual double GetResult()=0;
};
class OperationAdd:public Operation {
public:
double GetResult() override {
return double_numberA + double_numberB;
}
};
class OperationSub :public Operation {
public:
double GetResult() override {
return double_numberA - double_numberB;
}
};
class OperationFactory {
public:
static Operation* createOperate(char operate) {
Operation *oper =nullptr;
switch (operate) {
case '+':
oper = new OperationAdd;
break;
case '-':
oper = new OperationSub;
break;
default:
oper = nullptr;
break;
}
return oper;
}
};
int main() {
Operation* oper;
oper = OperationFactory::createOperate('+');
oper->double_numberA = 1.0;
oper->double_numberB = 2.0;
double result = oper->GetResult();
printf("%f\n", result);
}
GO
package main
import "fmt"
type Operation interface {
GetResult() float64
}
type field struct {
NumberA float64
NumberB float64
}
type OperationAdd struct {
field
}
type OperationSub struct {
field
}
func (oper *OperationAdd) GetResult() float64 {
return oper.NumberA + oper.NumberB
}
func (oper *OperationSub) GetResult() float64 {
return oper.NumberA - oper.NumberB
}
func createOperate(operate string) Operation {
switch operate {
case "+":
return &OperationAdd{}
case "-":
return &OperationSub{}
default:
return nil
}
}
func main() {
var OperFa Operation
OperFa = createOperate("+")
Oper := OperFa.(*OperationAdd)
Oper.NumberA = 1.0
Oper.NumberB = 2.0
result := OperFa.GetResult()
fmt.Println(result)
}
|