一、大话设计模式 之 简单工厂模式
来源:互联网 发布:机械战警玩具编程 编辑:程序博客网 时间:2024/06/06 13:09
模式特点:工厂根据条件产生不同功能的类。
程序实例:四则运算计算器,根据用户的输入产生相应的运算类,用这个运算类处理具体的运算。
package mainimport ("fmt")//BaseOperation接口type Operation interface {getResult() float64SetNumA(float64)SetNumB(float64)}type BaseOperation struct {numberA float64numberB float64}func (operation *BaseOperation) SetNumA(numA float64) {operation.numberA = numA}func (operation *BaseOperation) SetNumB(numB float64) {operation.numberB = numB}type OperationAdd struct {BaseOperation}func (this *OperationAdd) getResult() float64 {return this.numberA + this.numberB}type OperationSub struct {BaseOperation}func (this *OperationSub) getResult() float64 {return this.numberA - this.numberB}type OperationMul struct {BaseOperation}func (this *OperationMul) getResult() float64 {return this.numberA * this.numberB}type OperationDiv struct {BaseOperation}func (this *OperationDiv) getResult() float64 {if this.numberB == 0 {panic("被除数不能为0")}return this.numberA / this.numberB}type OperationFactory struct {}func (this *OperationFactory) createOperation(operator string) (operation Operation) {switch operator {case"+":operation = new(OperationAdd)case"-":operation = new(OperationSub)case"/":operation = new(OperationDiv)case"*":operation = new(OperationMul)default:panic("运算符号错误!")}return}func main() {defer func() {if err := recover(); err != nil {fmt.Println(err)}}()var fac OperationFactoryoper := fac.createOperation("/")oper.SetNumA(3.0)oper.SetNumB(0.0)fmt.Println(oper.getResult())}
0 0
- <一>读<<大话设计模式>>之简单工厂模式
- 一、大话设计模式 之 简单工厂模式
- <一>大话设计模式之简单工厂模式
- 大话设计模式(一)简单工厂模式
- 大话设计模式一:简单工厂模式
- 大话设计模式之简单工厂模式
- 大话设计模式之简单工厂模式
- 大话设计模式之简单工厂模式
- 大话设计模式之简单工厂模式
- 大话设计模式之--简单工厂模式
- 大话设计模式之简单工厂模式
- 《大话设计模式》之简单工厂模式
- 大话设计之简单工厂模式
- 大话设计模式读书笔记之简单工厂
- 大话设计模式一——简单工厂模式
- 大话设计模式一:简单工厂模式(simple factory)
- 大话设计模式读书笔记(一) 简单工厂模式
- 大话设计模式之简单工厂模式、抽象工厂模式及工厂方法模式的比较
- openni+nite体感鼠标模拟
- nodejs群聊和私聊
- html2--列表的标记
- Genymotion模拟器运行白屏
- 数码时钟
- 一、大话设计模式 之 简单工厂模式
- 【详解】CSS hack大全
- 判断主程序是Windows应用程序还是控制台应用程序
- js中window.location.search的用法和作用。
- TopShelf-(02)服务-01.安装.bat
- Magento: Fatal error: Cannot override final method Mage_Core_Model_Abstract::clearInstance()
- Android 更改纯色背景图片颜色,可实现一张背景圆形图片展示不同颜色
- (LeetCode)First Bad Version --- 查找坏版本
- 要怎样努力,才能成为很厉害的人