既然工厂模式每个产品都需要实现对应的工厂类去生成相关实例,提取产品的共性,提高代码的内聚性,
就是抽象工厂模式要干的。在抽象工厂中,依然是不同产品对应不同的工厂类,但可以尽可能将具有相同共性的产品类别合在一起,
从而提高了内聚性。但同时也带来一些问题,比如修改产品类,可能涉及到对应的工厂类都需要改动,OCP原则有没有很好的遵守,
而且通过更加地抽象化,也增加了代码的理解难度。
type OrderMainDAO interface {SaveOrderMain()
}//OrderDetailDAO 为订单详情纪录
type OrderDetailDAO interface {SaveOrderDetail()
}//DAOFactory DAO 抽象模式工厂接口
type DAOFactory interface {CreateOrderMainDAO() OrderMainDAOCreateOrderDetailDAO() OrderDetailDAO
}// RDBMainDAO 为关系型数据库的OrderMainDAO实现
type RDBMainDAO struct{}func (*RDBMainDAO) SaveOrderMain() {fmt.Print("rdb main save\n")
}type RDBDetailDAO struct{}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{}//SaveOrderMain ...
func (*XMLMainDAO) SaveOrderMain() {fmt.Print("xml main save\n")
}//XMLDetailDAO XML存储
type XMLDetailDAO struct{}// SaveOrderDetail ...
func (*XMLDetailDAO) SaveOrderDetail() {fmt.Print("xml detail save")
}//XMLDAOFactory 是RDB 抽象工厂实现
type XMLDAOFactory struct{}func (*XMLDAOFactory) CreateOrderMainDAO() OrderMainDAO {return &XMLMainDAO{}
}func (*XMLDAOFactory) CreateOrderDetailDAO() OrderDetailDAO {return &XMLDetailDAO{}
}
测试方法
package abstractfactoryimport "testing"func getMainAndDetail(factory DAOFactory) {factory.CreateOrderMainDAO().SaveOrderMain()factory.CreateOrderDetailDAO().SaveOrderDetail()
}func ExampleRdbFactory() {var factory DAOFactoryfactory = &RDBDAOFactory{}getMainAndDetail(factory)
}func TestRDBFactory(t *testing.T) {var factory DAOFactoryfactory = &RDBDAOFactory{}getMainAndDetail(factory)
}func TestXMLDAOFactory(t *testing.T) {var factory DAOFactoryfactory = &XMLDAOFactory{}getMainAndDetail(factory)
}