Advertisement
spider68

factory method - go

Aug 2nd, 2023
1,193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.37 KB | Source Code | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. // Product interface
  8. type Product interface {
  9.     Use() string
  10. }
  11.  
  12. // ConcreteProductA is a type of Product
  13. type ConcreteProductA struct{}
  14.  
  15. // Use implements the Product interface for ConcreteProductA
  16. func (c ConcreteProductA) Use() string {
  17.     return "Using ConcreteProductA"
  18. }
  19.  
  20. // ConcreteProductB is another type of Product
  21. type ConcreteProductB struct{}
  22.  
  23. // Use implements the Product interface for ConcreteProductB
  24. func (c ConcreteProductB) Use() string {
  25.     return "Using ConcreteProductB"
  26. }
  27.  
  28. // Creator is the factory interface
  29. type Creator interface {
  30.     CreateProduct() Product
  31. }
  32.  
  33. // ConcreteCreatorA is a ConcreteCreator that creates ConcreteProductA
  34. type ConcreteCreatorA struct{}
  35.  
  36. // CreateProduct implements the Creator interface for ConcreteCreatorA
  37. func (c ConcreteCreatorA) CreateProduct() Product {
  38.     return ConcreteProductA{}
  39. }
  40.  
  41. // ConcreteCreatorB is another ConcreteCreator that creates ConcreteProductB
  42. type ConcreteCreatorB struct{}
  43.  
  44. // CreateProduct implements the Creator interface for ConcreteCreatorB
  45. func (c ConcreteCreatorB) CreateProduct() Product {
  46.     return ConcreteProductB{}
  47. }
  48.  
  49. func main() {
  50.     creatorA := ConcreteCreatorA{}
  51.     productA := creatorA.CreateProduct()
  52.     fmt.Println(productA.Use())
  53.  
  54.     creatorB := ConcreteCreatorB{}
  55.     productB := creatorB.CreateProduct()
  56.     fmt.Println(productB.Use())
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement