美文网首页
Golang中小类大对象的一种实现

Golang中小类大对象的一种实现

作者: _张晓龙_ | 来源:发表于2018-03-22 07:07 被阅读0次

小类大对象

软件设计本质是解决分与合的问题。我们先将系统分解成很多单一职责的小类,然后利用“依赖注入“(Golang)或多重继承(C++)的手段再将它们组合成对象。所以,类应该是小的,对象应该是大的

盲人摸象.png

类作为一种模块化手段,遵循高内聚低耦合,让软件易于应对变化,可以将类看做是领域对象拥有的职责或扮演的角色;对象作为一种领域对象的的直接映射,解决了过多的类带来的可理解性问题,让领域可以指导设计,设计真正反映领域,领域对象需要真正意义上的生命周期管理。

上帝类是糟糕的,但上帝对象却恰恰是我们所期盼的。就拿大象来说,它很大,大到可以为外部提供多种功能的服务,而对于每种不同的服务需要者,它就扮演不同的角色。对于不同个体,需要的是更加具体的服务,而不是一头大象,因而他也并不关心为他服务的事物背后是否是一头大象。

大象组件.png

注:小类大对象和DCI(Data, Context, Interaction)殊途同归。

转账问题

假设我们有下面的一个转账场景:

  • zhangsan123帐户中存了1000
  • lisi456帐户中存了200
  • zhangsan123lisi456转账300

我们先将系统分解成单一职责的类:


transfer-money-classes.png

上图中的类对应于DCI中的Methodful Roles,接口对应于DCI中的Methodless Roles

小类的实现

accountIdInfo类的实现

注:Golang中小写字母开头的标识符仅具有包内可见性。

//account_id_info.go
package domain

type AccountId string

type accountIdInfo struct {
    id AccountId
}

func newAccountIdInfo(id AccountId) *accountIdInfo {
    return &accountIdInfo{id}
}

func (a *accountIdInfo) getAccountId() AccountId {
    return a.id
}

balance类的实现

//balance.go
package domain

type Amount uint

type balance struct {
    amount Amount
}

func newBalance(amount Amount) *balance {
    return &balance{amount:amount}
}

func (b *balance) increase(amount Amount) {
    b.amount += amount
}

func (b *balance) decrease(amount Amount) {
    b.amount -= amount
}

func (b *balance) get() Amount {
    return b.amount
}

message接口的实现

//message.go
package domain

import "fmt"

type message interface {
    sendTransferToMsg(to *accountIdInfo, amount Amount)
    sendTransferFromMsg(from *accountIdInfo, amount Amount)
}

const msgPhone = 0
type msgType int

func newMessage(msgType msgType) message {
    if msgType == msgPhone {
        return &phone{}
    }
    return nil
}

type phone struct {

}

func (p *phone) sendTransferToMsg(to *accountIdInfo, amount Amount) {
    fmt.Println("phone: ", "send ", amount, " money to ", to.getAccountId())
}

func (p *phone) sendTransferFromMsg(from *accountIdInfo, amount Amount) {
    fmt.Println("phone: ", "receive ", amount, " money from ", from.getAccountId())
}

MoneySource类的实现

MoneySource类依赖于accountIdInfo类,balance类和message接口。

//money_source.go
package domain

import "fmt"

type MoneySource struct {
    accountIdInfo *accountIdInfo
    balance *balance
    message message
}

func newMoneySource(accountIdInfo *accountIdInfo, balance *balance, message message) *MoneySource {
    return &MoneySource{accountIdInfo:accountIdInfo, balance:balance, message:message}
}


func (m *MoneySource) TransferMoneyTo(to *MoneyDestination, amount Amount) {
    fmt.Println("start: ", m.accountIdInfo.getAccountId(), " has ", m.balance.get(), " money")
    if m.balance.get() < amount {
        panic("insufficient money!")
    }
    to.TransferMoneyFrom(m.accountIdInfo, amount)
    m.balance.decrease(amount)
    m.message.sendTransferToMsg(to.getAccountId(), amount)
    fmt.Println("end: ", m.accountIdInfo.getAccountId(), " has ", m.balance.get(), " money")
}

MoneyDestination类的实现

MoneyDestination类依赖于accountIdInfo类,balance类和message接口。

//money_destination.go
package domain

import "fmt"

type MoneyDestination struct {
    accountIdInfo *accountIdInfo
    balance *balance
    message message
}

func newMoneyDestination(accountIdInfo *accountIdInfo, balance *balance, message message) *MoneyDestination {
    return &MoneyDestination{accountIdInfo:accountIdInfo, balance:balance, message:message}
}

func (m *MoneyDestination) getAccountId() *accountIdInfo {
    return m.accountIdInfo
}

func (m *MoneyDestination) TransferMoneyFrom(from *accountIdInfo, amount Amount) {
    fmt.Println("start: ", m.accountIdInfo.getAccountId(), " has ", m.balance.get(), " money")
    m.balance.increase(amount)
    m.message.sendTransferFromMsg(from, amount)
    fmt.Println("end: ", m.accountIdInfo.getAccountId(), " has ", m.balance.get(), " money")
}

大对象的实现

Account对象的实现

//account.go
package domain

type Account struct {
    accountIdInfo *accountIdInfo
    balance *balance
    message message
    MoneySource *MoneySource
    MoneyDestination *MoneyDestination
}

func NewAccount(accountId AccountId, amount Amount) *Account {
    account := &Account{}
    account.accountIdInfo = newAccountIdInfo(accountId)
    account.balance = newBalance(amount)
    account.message = newMessage(msgPhone)
    account.MoneySource = newMoneySource(account.accountIdInfo, account.balance, account.message)
    account.MoneyDestination = newMoneyDestination(account.accountIdInfo, account.balance, account.message)
    return account
}

AccountRepo的实现

//account_repo.go
package domain

import "sync"

var inst *AccountRepo
var once sync.Once

type AccountRepo struct {
    accounts map[AccountId]*Account
    lock sync.RWMutex
}

func GetAccountRepo() *AccountRepo {
    once.Do(func() {
        inst = &AccountRepo{accounts: make(map[AccountId]*Account)}
    })
    return inst
}

func (a *AccountRepo) Add(account *Account) {
    a.lock.Lock()
    a.accounts[account.accountIdInfo.getAccountId()] = account
    a.lock.Unlock()
}

func (a *AccountRepo) Get(accountId AccountId) *Account {
    a.lock.RLock()
    account := a.accounts[accountId]
    a.lock.RUnlock()
    return account
}

func (a *AccountRepo) Remove(accountId AccountId) {
    a.lock.Lock()
    delete(a.accounts, accountId)
    a.lock.Unlock()
}

API的实现

CreateAccount函数的实现

//create_account.go
package api

import "transfer-money/domain"

func CreateAccount(accountId domain.AccountId, amount domain.Amount) {
    account := domain.NewAccount(accountId, amount)
    repo := domain.GetAccountRepo()
    repo.Add(account)
}

TransferMoney函数的实现

//transfer_money.go
package api

import "transfer-money/domain"

func TransferMoney(from domain.AccountId, to domain.AccountId, amount domain.Amount) {
    repo := domain.GetAccountRepo()
    src := repo.Get(from)
    dst := repo.Get(to)
    src.MoneySource.TransferMoneyTo(dst.MoneyDestination, amount)
}

测试

main函数的实现

//main.go
package main

import "transfer-money/api"

func main() {
    api.CreateAccount("zhangsan123", 1000)
    api.CreateAccount("lisi456", 200)
    api.TransferMoney("zhangsan123", "lisi456", 300)
}

运行结果

start:  zhangsan123  has  1000  money
start:  lisi456  has  200  money
phone:  receive  300  money from  zhangsan123
end:  lisi456  has  500  money
phone:  send  300  money to  lisi456
end:  zhangsan123  has  700  money

小结

本文以转账问题为例,给出了Golang中小类大对象的一种依赖注入实现,重点是Role的交织的姿势,希望对读者有一定的启发。

相关文章

  • Golang中小类大对象的一种实现

    小类大对象 软件设计本质是解决分与合的问题。我们先将系统分解成很多单一职责的小类,然后利用“依赖注入“(Golan...

  • Go语言结构体快速入门

    Golang里面没有类,用结构体实现面向对象的编程特性。非常简洁。没有extends,通过匿名字段来实现。Gola...

  • Golang 面向对象编程-非侵入式接口

    Golang 面向对象编程-非侵入式接口 在go语言中,一个类只需要实现了接口要求的所有函数,我们就说这个类实现了...

  • golang 使用组合的方式实现继承

    摘要 golang并非完全面向对象的程序语言,为了实现面向对象的继承这一神奇的功能,golang允许struct间...

  • 15 Golang结构体详解(一)

    Golang中没有“类”的概念,Golang中的结构体struct和其他语言中的类有点相似。和其他面向对象语言中的...

  • Java-动态代理的两种实现

    第一种:基本逻辑,代理类实现 InvocationHandler接口,代理类持有 实现类对象,提供创建代理类,在i...

  • Go 学习笔记 11 | Golang 接口详解

    一、Golang 接口 Golang 中接口定义了对象的行为规范,只定义规范不实现。接口中定义的规范由具体的对象来...

  • Go核心编程-面向对象 [OOP]

    Golang也是支持面向对象(OOP)编程特性的语言,但是Golang中没有类(class),而Go语言的结构体(...

  • 代理模式(Proxy)

    代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问。 主方法 接口类 实现类(被代理类) 代理类

  • Golang interface

    接口在Golang中表示一种抽象的数据类型,它用来定义对象的行为,具体的实现由对象决定。程序编写时如果仅仅定义接口...

网友评论

      本文标题:Golang中小类大对象的一种实现

      本文链接:https://www.haomeiwen.com/subject/cnloqftx.html