简介

建造者模式应用场景是

  • 类中的属性比较多
  • 类中的属性之间有一定的依赖关系,或者是约束关系
  • 存在必选和非必选的属性
  • 希望创建不可变的对象

与工厂模式区别是建造者模式常用于创建参数比较多的对象时候。常见的做法是必填参数直接传递,可选参数通过传递可变的方法进行创建

  1. package main
  2. const (
  3. defaultMaxTotal = 10
  4. defaultMaxIdle = 9
  5. defalutMinIdle = 1
  6. )
  7. type ResourcePoolConfig struct {
  8. name string
  9. maxTotal int
  10. maxIdle int
  11. minIdle int
  12. }
  13. type ResourcePoolConfigBuilder struct {
  14. name string
  15. maxTotal int
  16. maxIdle int
  17. minIdle int
  18. }
  19. func (b *ResourcePoolConfigBuilder) SetName(name string) error {
  20. if name == "" {
  21. return fmt.Errorf("name can not be empty")
  22. }
  23. b.name = name
  24. return nil
  25. }
  26. func (b *ResourcePoolConfigBuilder) SetMinIdle(minIdle int) error {
  27. if minIdle < 0 {
  28. return fmt.Errorf("max tatal cannot < 0, input: %d", minIdle)
  29. }
  30. b.minIdle = minIdle
  31. return nil
  32. }
  33. func (b *ResourcePoolConfigBuilder) SetMaxIdle(maxIdle int) error {
  34. if maxIdle < 0 {
  35. return fmt.Errorf("max tatal cannot < 0, input: %d", maxIdle)
  36. }
  37. b.maxIdle = maxIdle
  38. return nil
  39. }
  40. func (b *ResourcePoolConfigBuilder) SetMaxTotal(maxTotal int) error {
  41. if maxTotal < 0 {
  42. return fmt.Errorf("max tatal cannot <=0, input: %d", maxTotal)
  43. }
  44. b.maxTotal = maxTotal
  45. return nil
  46. }
  47. //Build Build
  48. func (b *ResourcePoolConfigBuilder) Build() (*ResourcePoolConfig, error) {
  49. if b.name == "" {
  50. return nil, fmt.Errorf("name can not be empty")
  51. }
  52. //设置默认值
  53. if b.minIdle == 0 {
  54. b.minIdle = defalutMinIdle
  55. }
  56. if b.maxIdle == 0 {
  57. b.maxIdle = defaultMaxIdle
  58. }
  59. if b.maxTotal == 0 {
  60. b.maxTotal = defaultMaxTotal
  61. }
  62. if b.maxTotal < b.maxIdle {
  63. return nil, fmt.Errorf("max total(%d) cannot < max idle(%d)", b.maxTotal, b.maxIdle)
  64. }
  65. if b.minIdle > b.maxIdle {
  66. return nil, fmt.Errorf("max idle(%d) cannot < min idle(%d)", b.maxIdle, b.minIdle)
  67. }
  68. return &ResourcePoolConfig{
  69. name: b.name,
  70. maxTotal: b.maxTotal,
  71. maxIdle: b.maxIdle,
  72. minIdle: b.minIdle,
  73. }, nil
  74. }