Go实战--Design Patterns in Golang 之工厂模式(简单工厂、工厂方法、抽象工厂)

前端之家收集整理的这篇文章主要介绍了Go实战--Design Patterns in Golang 之工厂模式(简单工厂、工厂方法、抽象工厂)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

先看一下golang的Tiobe指数趋势:

可以看到在2017年7月,达到了最高点,之后略有下降。我坚信,2018年的7月,golang还会飙升。

生命不止,继续 go go go !!!

继续,golang中设计模式的探讨。
按照国际惯例,讲完单例模式,接下来就该轮到工厂模式。还是那句话,每个人对设计模式的理解都有所不同,欢迎各位探讨。

何为工厂模式

WIKI:
In class-based programming,the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.

百度百科:
工厂模式是我们最常用的实例化对象模式了,是用工厂方法代替new操作的一种模式。

在面向对象的编程语言中(如java,C++)设计模式的概念广为人知,应用的也非常广泛。设计模式让我们的代码变得灵活起来,具有很强的扩展性。但在与C语言比肩的Go语言中,设计模式的概念并没有十分突出,甚至很少听到。在Go的开发中,借鉴design pattern的理念同样回味无穷我们的开发带来极大的便利。

c++中使用工厂模式
纯虚类:

  1. class IAnimal
  2. {
  3. public:
  4. virtual int GetNumberOfLegs() const = 0;
  5. virtual void Speak() = 0;
  6. virtual void Free() = 0;
  7. };

实现类:

  1. // IAnimal implementations
  2. class Cat : public IAnimal
  3. {
  4. public:
  5. int GetNumberOfLegs() const { return 4; }
  6. void Speak() { cout << "Meow" << endl; }
  7. void Free() { delete this; }
  8.  
  9. static IAnimal * __stdcall Create() { return new Cat(); }
  10. };
  11.  
  12. class Dog : public IAnimal
  13. {
  14. public:
  15. int GetNumberOfLegs() const { return 4; }
  16. void Speak() { cout << "Woof" << endl; }
  17. void Free() { delete this; }
  18.  
  19. static IAnimal * __stdcall Create() { return new Dog(); }
  20. };
  21.  
  22. class Spider : public IAnimal // Yeah it isn’t really an animal…
  23. {
  24. public:
  25. int GetNumberOfLegs() const { return 8; }
  26. void Speak() { cout << endl; }
  27. void Free() { delete this; }
  28.  
  29. static IAnimal * __stdcall Create() { return new Spider(); }
  30. };
  31.  
  32. class Horse : public IAnimal
  33. {
  34. public:
  35. int GetNumberOfLegs() const { return 4; }
  36. void Speak() { cout << "A horse is a horse,of course,of course." << endl; }
  37. void Free() { delete this; }
  38.  
  39. static IAnimal * __stdcall Create() { return new Horse(); }
  40. };

工厂类:

  1. class AnimalFactory
  2. {
  3. private:
  4. AnimalFactory();
  5. AnimalFactory(const AnimalFactory &) { }
  6. AnimalFactory &operator=(const AnimalFactory &) { return *this; }
  7.  
  8. typedef map FactoryMap;
  9. FactoryMap m_FactoryMap;
  10. public:
  11. ~AnimalFactory() { m_FactoryMap.clear(); }
  12.  
  13. static AnimalFactory *Get()
  14. {
  15. static AnimalFactory instance;
  16. return &instance;
  17. }
  18.  
  19. void Register(const string &animalName,CreateAnimalFn pfnCreate);
  20. IAnimal *CreateAnimal(const string &animalName);
  21. };

工厂类实现:

  1. AnimalFactory::AnimalFactory()
  2. {
  3. Register("Horse",&Horse::Create);
  4. Register("Cat",&Cat::Create);
  5. Register("Dog",&Dog::Create);
  6. Register("Spider",&Spider::Create);
  7. }
  8.  
  9. void AnimalFactory::Register(const string &animalName,CreateAnimalFn pfnCreate)
  10. {
  11. m_FactoryMap[animalName] = pfnCreate;
  12. }
  13.  
  14. IAnimal *AnimalFactory::CreateAnimal(const string &animalName)
  15. {
  16. FactoryMap::iterator it = m_FactoryMap.find(animalName);
  17. if( it != m_FactoryMap.end() )
  18. return it->second();
  19. return NULL;
  20. }

使用:

  1. int main( int argc,char **argv )
  2. {
  3. IAnimal *pAnimal = NULL;
  4. string animalName;
  5.  
  6. while( pAnimal == NULL )
  7. {
  8. cout << "Type the name of an animal or ‘q’ to quit: ";
  9. cin >> animalName;
  10.  
  11. if( animalName == "q" )
  12. break;
  13.  
  14. IAnimal *pAnimal = AnimalFactory::Get()->CreateAnimal(animalName);
  15. if( pAnimal )
  16. {
  17. cout << "Your animal has " << pAnimal->GetNumberOfLegs() << " legs." << endl;
  18. cout << "Your animal says: ";
  19. pAnimal->Speak();
  20. }
  21. else
  22. {
  23. cout << "That animal doesn’t exist in the farm! Choose another!" << endl;
  24. }
  25. if( pAnimal )
  26. pAnimal->Free();
  27. pAnimal = NULL;
  28. animalName.clear();
  29. }
  30. return 0;
  31. }

Struct and Interface

我们知道,golang不是完全的面向对象语言,没有C++或是java中所谓的类。

但是,有struct和interface。这两个知识点是必须要掌握的,弄明白了他们还能理解如何在golang中使用设计模式。

struct:

  1. type exampleStruct struct{
  2. num int
  3. s string
  4. flag bool
  5. }

Go语言学习之struct(The way to go)

interface:

  1. type myInterface interface { myFunction() float64 }

Go语言学习之interface(The way to go)

简单工厂、工厂方法、抽象工厂

Stack Overflow:
https://stackoverflow.com/questions/13029261/design-patterns-factory-vs-factory-method-vs-abstract-factory

简单工厂
简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。

Simple Factory Pattern
Definition:
Creates objects without exposing the instantiation logic to the client.
Refers to the newly created object through a common interface

工厂方法
工厂方法是针对每一种产品提供一个工厂类。通过不同的工厂实例来创建不同的产品实例。
在同一等级结构中,支持增加任意产品。

Factory Method
Definition:
Defines an interface for creating objects,but let subclasses to decide which class to instantiate
Refers the newly created object through a common interface.

抽象工厂
抽象工厂是应对产品族概念的。比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法

Abstract Factory
Definition:
Abstract Factory offers the interface for creating a family of related objects,without explicitly specifying their classes

golang中简单工厂模式

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. )
  6.  
  7. type Operater interface {
  8. Operate(int,int) int
  9. }
  10.  
  11. type AddOperate struct {
  12. }
  13.  
  14. func (this *AddOperate) Operate(rhs int,lhs int) int {
  15. return rhs + lhs
  16. }
  17.  
  18. type MultipleOperate struct {
  19. }
  20.  
  21. func (this *MultipleOperate) Operate(rhs int,lhs int) int {
  22. return rhs * lhs
  23. }
  24.  
  25. type OperateFactory struct {
  26. }
  27.  
  28. func NewOperateFactory() *OperateFactory {
  29. return &OperateFactory{}
  30. }
  31.  
  32. func (this *OperateFactory) CreateOperate(operatename string) Operater {
  33. switch operatename {
  34. case "+":
  35. return &AddOperate{}
  36. case "*":
  37. return &MultipleOperate{}
  38. default:
  39. panic("无效运算符号")
  40. return nil
  41. }
  42. }
  43.  
  44. func main() {
  45. Operator := NewOperateFactory().CreateOperate("+")
  46. fmt.Printf("add result is %d\n",Operator.Operate(1, 2))
  47. }

golang中工厂方法模式

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. )
  6.  
  7. type Operation struct {
  8. a float64
  9. b float64
  10. }
  11.  
  12. type OperationI interface {
  13. GetResult() float64
  14. SetA(float64)
  15. SetB(float64)
  16. }
  17.  
  18. func (op *Operation) SetA(a float64) {
  19. op.a = a
  20. }
  21.  
  22. func (op *Operation) SetB(b float64) {
  23. op.b = b
  24. }
  25.  
  26. type AddOperation struct {
  27. Operation
  28. }
  29.  
  30. func (this *AddOperation) GetResult() float64 {
  31. return this.a + this.b
  32. }
  33.  
  34. type SubOperation struct {
  35. Operation
  36. }
  37.  
  38. func (this *SubOperation) GetResult() float64 {
  39. return this.a - this.b
  40. }
  41.  
  42. type MulOperation struct {
  43. Operation
  44. }
  45.  
  46. func (this *MulOperation) GetResult() float64 {
  47. return this.a * this.b
  48. }
  49.  
  50. type DivOperation struct {
  51. Operation
  52. }
  53.  
  54. func (this *DivOperation) GetResult() float64 {
  55. return this.a / this.b
  56. }
  57.  
  58. type IFactory interface {
  59. CreateOperation() Operation
  60. }
  61.  
  62. type AddFactory struct {
  63. }
  64.  
  65. func (this *AddFactory) CreateOperation() OperationI {
  66. return &(AddOperation{})
  67. }
  68.  
  69. type SubFactory struct {
  70. }
  71.  
  72. func (this *SubFactory) CreateOperation() OperationI {
  73. return &(SubOperation{})
  74. }
  75.  
  76. type MulFactory struct {
  77. }
  78.  
  79. func (this *MulFactory) CreateOperation() OperationI {
  80. return &(MulOperation{})
  81. }
  82.  
  83. type DivFactory struct {
  84. }
  85.  
  86. func (this *DivFactory) CreateOperation() OperationI {
  87. return &(DivOperation{})
  88. }
  89.  
  90. func main() {
  91. fac := &(AddFactory{})
  92. oper := fac.CreateOperation()
  93. oper.SetA(1)
  94. oper.SetB(2)
  95. fmt.Println(oper.GetResult())
  96. }

更具体的例子:
http://matthewbrown.io/2016/01/23/factory-pattern-in-golang/

golang中抽象工厂模式

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. type GirlFriend struct {
  6. nationality string
  7. eyesColor string
  8. language string
  9. }
  10.  
  11. type AbstractFactory interface {
  12. CreateMyLove() GirlFriend
  13. }
  14.  
  15. type IndianGirlFriendFactory struct {
  16. }
  17.  
  18. type KoreanGirlFriendFactory struct {
  19. }
  20.  
  21. func (a IndianGirlFriendFactory) CreateMyLove() GirlFriend {
  22. return GirlFriend{"Indian","Black","Hindi"}
  23. }
  24.  
  25. func (a KoreanGirlFriendFactory) CreateMyLove() GirlFriend {
  26. return GirlFriend{"Korean","Brown","Korean"}
  27. }
  28.  
  29. func getGirlFriend(typeGf string) GirlFriend {
  30.  
  31. var gffact AbstractFactory
  32. switch typeGf {
  33. case "Indian":
  34. gffact = IndianGirlFriendFactory{}
  35. return gffact.CreateMyLove()
  36. case "Korean":
  37. gffact = KoreanGirlFriendFactory{}
  38. return gffact.CreateMyLove()
  39. }
  40. return GirlFriend{}
  41. }
  42.  
  43. func main() {
  44.  
  45. a := getGirlFriend("Indian")
  46.  
  47. fmt.Println(a.eyesColor)
  48. }

猜你在找的Go相关文章