四则运算--Go interface

package main

import "fmt"

//定义接口
type Opter interface {
    Result() int
}

//父类
type Operate struct {
    n1 int
    n2 int
}

//加法子类
type Add struct {
    Operate
}

//减法子类
type Sub struct {
    Operate
}

//乘法子类
type Mul struct {
    Operate
}

//除法子类
type Div struct {
    Operate
}

//工厂类
type Factory struct {
}

//工厂方法
//func (f *Factory)CreateFactory(n1 int, n2 int, ch string) int
func CreateFactory(n1 int, n2 int, ch string) int {
    //接口定义
    var o Opter
    switch ch {
    case "+":
        a := Add{Operate{n1, n2}}
        o = &a
    case "-":
        s := Sub{Operate{n1, n2}}
        o = &s
    case "*":
        m := Mul{Operate{n1, n2}}
        o = &m
    case "/":
        d := Div{Operate{n1, n2}}
        o = &d

    }
    //调用多态
    //return Result(o)
    return o.Result()
}

//加法子类方法
func (a *Add) Result() int {
    return a.n1 + a.n2
}

//减法子类方法
func (s *Sub) Result() int {
    return s.n1 - s.n2
}

//乘法子类方法
func (m *Mul) Result() int {
    return m.n1 * m.n2
}

//除法子类方法
func (d *Div) Result() int {
    //除法中 除数不能为0
    return d.n1 / d.n2
}

//多态实现
func Result(o Opter) int {
    value := o.Result()
    return value
}

//面向对象实现
func main0201() {
    //加法运算
    //a := Add{Operate{10, 20}}
    //value := a.Result()
    //fmt.Println(value)

    //减法运算
    s := Sub{Operate{10, 20}}
    value := s.Result()
    fmt.Println(value)
}

//面向接口实现
func main0202() {
    //创建加法对象
    //a := Add{Operate{10, 20}}
    //创建减法对象
    s := Sub{Operate{10, 20}}

    //定义接口
    var o Opter
    o = &s
    value := o.Result()
    fmt.Println(value)
}

//面向多态实现
func main0203() {
    //创建加法对象
    //a := Add{Operate{10, 20}}
    //创建减法对象
    //s := Sub{Operate{10, 20}}

    //创建乘法对象
    m := Mul{Operate{10, 20}}

    //调用多态
    value := Result(&m)
    fmt.Println(value)
}

//面向设计模式实现(工厂设计模式)
//基于面向对象分成三个模块  M (模型)V (视图) C(控制器)
func main() {

    //创建工厂对象
    //var f Factory
    //value := f.CreateFactory(100, 20, "/")
    //通过函数实现
    value := CreateFactory(100, 20, "/")
    fmt.Println(value)
}

你可能感兴趣的:(四则运算--Go interface)