UML
classDiagram
class Product {
<!--more-->
<<interface>>
+operation()
}
class ConcreteProductA {
+operation()
}
class ConcreteProductB {
+operation()
}
class SimpleFactory {
+createProduct(string) Product
}
Product <|.. ConcreteProductA
Product <|.. ConcreteProductB
SimpleFactory ..> Product
SimpleFactory ..> ConcreteProductA
SimpleFactory ..> ConcreteProductB
````
# Go Sample
package main
import "fmt"
// Product 接口
type Product interface {
Operation() string
}
// ConcreteProductA 结构体
type ConcreteProductA struct{}
func (p *ConcreteProductA) Operation() string {
return "ConcreteProductA"
}
// ConcreteProductB 结构体
type ConcreteProductB struct{}
func (p *ConcreteProductB) Operation() string {
return "ConcreteProductB"
}
// SimpleFactory 结构体
type SimpleFactory struct{}
func (f *SimpleFactory) CreateProduct(productType string) Product {
switch productType {
case "A":
return &ConcreteProductA{}
case "B":
return &ConcreteProductB{}
default:
return nil
}
}
func main() {
factory := &SimpleFactory{}
productA := factory.CreateProduct("A")
fmt.Println(productA.Operation())
productB := factory.CreateProduct("B")
fmt.Println(productB.Operation())
}