抽象工厂模式
抽象工厂模式用户生成产品族的工厂, 所生成的对象是有关联的. 如果抽象工厂退化成生成的对象无关联则成为工厂函数模式.
比如本例子中使用RDB和XML 存储订单信息, 抽象工厂分别能生成相关的主订单信息和订单详情信息. 如果业务逻辑中需要替换使用的时候只需要改动工厂函数相关的类就能替换使用不同的存储方式.
abstractfactory.go
抽象工厂函数:
package abstractfactory
import "fmt"
//OrderMainDAO 为订单主记录
type OrderMainDAO interface {
SaveOrderMain()
}
//OrderDetailDAO 为订单详情记录
type OrderDetailDAO interface {
SaveOrderDetail()
}
//DAOFactory DAO 抽象工厂接口
type DAOFactory interface {
CreateOrderMainDAO() OrderMainDAO
CreateOrderDetailDAO() OrderDetailDAO
}
//RDBMainDAO 为关系数据库的OrderMainDAO实现
type RDBMainDAO struct{}
//SaveOrderMain ...
func (*RDBMainDAO) SaveOrderMain() {
fmt.Print("rdb main save \n")
}
//RDBDetailDAO为关系数据库的OrderDetailDAO实现
type RDBDetailDAO struct{}
//SaveOrderDetail ...
func (*RDBDetailDAO) SaveOrderDetail() {
fmt.Print("rdb detail save \n")
}
//RDBDAOFactory 是RDB 抽象工厂实现
type RDBDAOFactory struct{}
func (*RDBDAOFactory) CreateOrderMainDAO() OrderMainDAO {
return &RDBMainDAO{}
}
func (*RDBDAOFactory) CreateOrderDetailDAO() OrderDetailDAO {
return &RDBDetailDAO{}
}
// XMLMainDAO XML存储
type XMLMainDAO struct{}
func (*XMLMainDAO) SaveOrderMain() {
fmt.Print("xml main save \n")
}
//SaveOrderDetail ...
type XMLOrderDetailDAO struct{}
func (*XMLOrderDetailDAO) SaveOrderDetail() {
fmt.Print("xml detail save")
}
//XMLDAOFactory 是RDB 抽象工厂实现
type XMLDAOFactory struct{}
func (*XMLDAOFactory) CreateOrderMainDAO() OrderMainDAO {
return &XMLMainDAO{}
}
func (*XMLDAOFactory) CreateOrderDetailDAO() OrderDetailDAO {
return &XMLOrderDetailDAO{}
}
测试代码abstractfactory_test.go
:
package abstractfactory
import "testing"
func getMainAndDetail(factory DAOFactory) {
factory.CreateOrderMainDAO().SaveOrderMain()
factory.CreateOrderDetailDAO().SaveOrderDetail()
}
func TestRdbFactory(t *testing.T) {
var factory DAOFactory
factory = &RDBDAOFactory{}
getMainAndDetail(factory)
}
func TestXmlFactory(t *testing.T) {
var factory DAOFactory
factory = &XMLDAOFactory{}
getMainAndDetail(factory)
}
执行结果如下:
~/G/s/l/g/abstract_factory go test -v 473ms 三 7/ 3 15:42:54 2019
=== RUN TestRdbFactory
rdb main save
rdb detail save
--- PASS: TestRdbFactory (0.00s)
=== RUN TestXmlFactory
xml main save
xml detail save--- PASS: TestXmlFactory (0.00s)
PASS
ok _/Users/finup/GoglandProjects/src/learn-demo/golang-design/abstract_factory 0.006s
「真诚赞赏,手留余香」
真诚赞赏,手留余香
使用微信扫描二维码完成支付
