设计模式--->简单工厂模式01

简单工厂模式

思想

继承,多态,封装
可维护—可复用—可扩展—灵活性好

面对对象的编程,并不是类越多越好,类的划分是为了封装但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类

封装:将业务逻辑与界面逻辑分开,让它们之间的耦合度下降
继承:不同的运算继承运算类,使得拓展简单安全
多态:通过多态,返回父类的方法实现了计算器的结果

工厂:如何让计算机知道我希望用哪一个算法?到底要实例化谁,用一个单独的类来做这个创造实例,工厂会实例化出合适的对象
在这里插入图片描述

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)
}
posted @ 2021-09-11 23:33  cheems~  阅读(23)  评论(0编辑  收藏  举报