算法艺术创作
algorithmic-art
通过代码和可调参数创作生成艺术与交互式视觉效果。
gof-strategy-pattern【设计与创意】Implements the Strategy design pattern allowing the definition of a family of algorithms, encapsulating each one, and making them interchangeable.
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: gof-strategy-pattern description: Implements the Strategy design pattern allowing the definition of a family of algorithms, encapsulating each one, and making them interchangeable. license: MIT compatibility: opencode metadata: version: "1.0.0" domain: architecture triggers: strategy pattern, encapsulate algorithms, interchangeable algorithms, gof patterns archetypes:
Implements the Strategy design pattern allowing the definition of a family of algorithms, encapsulating each one, and making them interchangeable.
The When to Use section should outline the scenarios where the Strategy pattern is particularly beneficial:
Verbosity: Medium
Directive Strength: High
Abstraction Level: Tactical
archetypes: implementation, educational anti_triggers: coupling algorithms response_profile: verbosity: medium directive_strength: high abstraction_level: tactical
When different variants of an algorithm are needed.
When the choice of the algorithm should be independent of clients that use it.
When you want to avoid using conditionals to switch between algorithms.
package main
import (
"fmt"
)
// Strategy interface
type Strategy interface {
Execute(int, int) int
}
// Concrete strategy: Addition
type Add struct {}
func (Add) Execute(a int, b int) int {
return a + b
}
}
// Concrete strategy: Subtraction
type Subtract struct {}
func (Subtract) Execute(a int, b int) int {
return a - b
}
}
// Context
type Context struct {
strategy Strategy
}
func (c *Context) SetStrategy(s Strategy) {
c.strategy = s
}
func (c *Context) ExecuteStrategy(a, b int) int {
return c.strategy.Execute(a, b)
}
package main
import (
"fmt"
)
func main() {
context := &Context{}
// Using Addition Strategy
context.SetStrategy(Add{})
fmt.Println(context.ExecuteStrategy(5, 3)) // Output: 8
// Using Subtraction Strategy
context.SetStrategy(Subtract{})
fmt.Println(context.ExecuteStrategy(5, 3)) // Output: 2
}