senghoo/golang-design-pattern
设计模式 Golang实现-《研磨设计模式》读书笔记
Healthy across all four use cases
weakest axisPermissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit 7mo ago
- ✓12 active contributors
- ✓MIT licensed
Show all 7 evidence items →Show less
- ✓CI configured
- ⚠Slowing — last commit 7mo ago
- ⚠Concentrated ownership — top contributor handles 76% of recent commits
- ⚠No test directory detected
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/senghoo/golang-design-pattern)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/senghoo/golang-design-pattern on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: senghoo/golang-design-pattern
Generated by RepoPilot · 2026-05-09 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/senghoo/golang-design-pattern shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across all four use cases
- Last commit 7mo ago
- 12 active contributors
- MIT licensed
- CI configured
- ⚠ Slowing — last commit 7mo ago
- ⚠ Concentrated ownership — top contributor handles 76% of recent commits
- ⚠ No test directory detected
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live senghoo/golang-design-pattern
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/senghoo/golang-design-pattern.
What it runs against: a local clone of senghoo/golang-design-pattern — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in senghoo/golang-design-pattern | Confirms the artifact applies here, not a fork |
| 2 | License is still MIT | Catches relicense before you depend on it |
| 3 | Default branch master exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 234 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of senghoo/golang-design-pattern. If you don't
# have one yet, run these first:
#
# git clone https://github.com/senghoo/golang-design-pattern.git
# cd golang-design-pattern
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of senghoo/golang-design-pattern and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "senghoo/golang-design-pattern(\\.git)?\\b" \\
&& ok "origin remote is senghoo/golang-design-pattern" \\
|| miss "origin remote is not senghoo/golang-design-pattern (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(MIT)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"MIT\"" package.json 2>/dev/null) \\
&& ok "license is MIT" \\
|| miss "license drift — was MIT at generation time"
# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
&& ok "default branch master exists" \\
|| miss "default branch master no longer exists"
# 4. Critical files exist
test -f "README.md" \\
&& ok "README.md" \\
|| miss "missing critical file: README.md"
test -f "00_simple_factory/simple.go" \\
&& ok "00_simple_factory/simple.go" \\
|| miss "missing critical file: 00_simple_factory/simple.go"
test -f "04_factory_method/factorymethod.go" \\
&& ok "04_factory_method/factorymethod.go" \\
|| miss "missing critical file: 04_factory_method/factorymethod.go"
test -f "03_singleton/singleton.go" \\
&& ok "03_singleton/singleton.go" \\
|| miss "missing critical file: 03_singleton/singleton.go"
test -f "15_strategy/strategy.go" \\
&& ok "15_strategy/strategy.go" \\
|| miss "missing critical file: 15_strategy/strategy.go"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 234 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~204d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/senghoo/golang-design-pattern"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
A comprehensive Go implementation reference for 23+ Gang of Four design patterns, organized as study notes from the book '研磨设计模式' (Refactoring to Design Patterns). Each pattern lives in its own directory with working code examples, unit tests, and a README explaining the pattern's purpose and Go-specific implementation details. Flat, pattern-focused directory structure: 23 numbered directories (00_simple_factory through 23_visitor) each containing a pattern implementation. Each directory has three files: README.md (explanation), patternname.go (implementation), and patternname_test.go (unit tests). No external dependencies—pure Go stdlib examples.
👥Who it's for
Go developers learning design patterns—particularly intermediate engineers transitioning from other languages who need concrete, runnable examples of how classic OOP patterns translate to idiomatic Go (interfaces, goroutines, struct composition). Also useful for code reviewers and architects designing Go systems.
🌱Maturity & risk
Actively maintained but stable. The repo has passing CI (Travis-CI configured in .travis.yml), comprehensive test coverage (every pattern has a *_test.go file), and appears to be a learning resource rather than a production library. Last activity unclear from file list, but the scope is well-defined and complete—unlikely to break.
Low risk for a reference project. Single maintainer (senghoo) with no dependencies listed—just Go stdlib. The repo is read-heavy (patterns won't change), so no production stability concerns. Main risk is the repo serves educational purposes only; don't copy-paste for production without understanding the context and Go idioms.
Active areas of work
No active development signals visible from file list. This appears to be a completed reference project—all 23 patterns are implemented with tests and documentation. It serves as a stable study guide rather than a project with ongoing feature work.
🚀Get running
git clone https://github.com/senghoo/golang-design-pattern.git
cd golang-design-pattern
go test ./... # Run all pattern tests
go test ./03_singleton -v # Run a specific pattern's tests
Daily commands:
There is no server or CLI to run. This is a reference library. To understand a pattern: (1) read the README in the pattern directory, (2) examine the implementation in patternname.go, (3) run the tests with go test ./XX_patternname -v to see behavior.
🗺️Map of the codebase
README.md— Entry point documenting all 23 design patterns with links to implementations; essential for understanding the repo's scope and organization.00_simple_factory/simple.go— Foundational creational pattern; demonstrates the simplest factory pattern that newer contributors should understand before exploring more complex variations.04_factory_method/factorymethod.go— Core pattern showing method-based factory design; illustrates the key difference from simple factory and is frequently referenced in creational discussions.03_singleton/singleton.go— Critical for understanding thread-safe object instantiation in Go; singleton pattern is widely used across production codebases.15_strategy/strategy.go— Behavioral pattern enabling algorithm selection at runtime; demonstrates Go's interface-driven design philosophy central to the codebase.01_facade/facade.go— Structural pattern simplifying complex subsystem interaction; shows how to design clean APIs in Go—a key architectural principle..travis.yml— CI/CD configuration ensuring all 23 pattern implementations pass tests; critical for validating pattern correctness across code changes.
🧩Components & responsibilities
- Creational patterns (6 implementations) (Go structs, interfaces, constructors) — Manage object instantiation mechanisms; handle initialization, cloning, and family-based creation without tight coupling
- Failure mode: Incorrect instantiation visibility or thread-unsafe initialization; shared state in singletons
- Structural patterns (7 implementations) (Go embedding, interface composition, wrapper types) — Compose objects into larger structures; provide interface adaptation, delegation, and composition without breaking encapsulation
- Failure mode: Incorrect delegation chains; memory overhead from excessive wrapper layers; interface mismatch in adapters
- Behavioral patterns (10 implementations) (Go function types,) — Define communication protocols between objects; encapsulate requests, distribute responsibilities, and decouple senders from receivers
🛠️How to make changes
Add a new design pattern implementation
- Create a new directory following the naming convention: NN_pattern_name (e.g., 24_responsibility_chain) (
README.md) - Implement the pattern in a main Go file (e.g., pattern.go) with exported types and functions demonstrating the pattern (
NN_pattern_name/pattern.go) - Write unit tests in pattern_test.go validating core behavior and use cases (
NN_pattern_name/pattern_test.go) - Create a README.md in the pattern directory explaining the pattern intent, structure, and Go-specific implementation details (
NN_pattern_name/README.md) - Update the main README.md to add the new pattern to its appropriate category (创建型/结构型/行为型) (
README.md)
Add a variant of an existing pattern
- Open the existing pattern implementation (e.g., 03_singleton/singleton.go) (
03_singleton/singleton.go) - Add a new type or function implementing the variant (e.g., lazy-loaded singleton, eager singleton) (
03_singleton/singleton.go) - Add corresponding test cases in the pattern's _test.go file (
03_singleton/singleton_test.go) - Update the pattern's README.md to document the new variant and when to use it (
03_singleton/README.md)
Run and verify all pattern tests
- Execute
go test ./...from the repository root to run all 23 pattern test suites (.travis.yml) - Each pattern directory contains a _test.go file with TestXxx functions verifying correct behavior (
00_simple_factory/simple_test.go) - Verify tests pass in CI pipeline (check .travis.yml for exact test command and environment) (
.travis.yml)
🔧Why these technologies
- Go (Golang) — Lightweight compiled language with built-in concurrency support; interfaces enable clean implementation of behavioral patterns; demonstrates modern language idioms.
- Travis CI (.travis.yml) — Provides continuous integration validation ensuring all 23 pattern implementations remain correct across code changes and Go versions.
- Go testing package (std lib) — Zero-dependency testing framework built into Go standard library; patterns focus on core logic without mocking frameworks.
⚖️Trade-offs already made
-
Each pattern in its own directory with isolated implementation
- Why: Maximizes clarity and maintainability; allows learners to study patterns independently without navigating complex shared code.
- Consequence: Some utility code may be duplicated across patterns; minimal code reuse enforces learning by explicit pattern implementation.
-
Simple test files without mocking libraries or complex fixtures
- Why: Focuses on pattern correctness without introducing testing framework complexity; makes examples accessible to learners.
- Consequence: Tests demonstrate patterns in isolation; real-world usage patterns requiring mocks or fixtures aren't shown; encourages readers to extend examples.
-
Numeric prefixes (00_, 04_, 15_) for pattern directories rather than alphabetical
- Why: Allows flexible grouping by pattern type (creational, structural, behavioral) while maintaining suggested learning order.
- Consequence: Directory listing doesn't reflect alphabetical order; requires consulting README for pattern categorization.
🚫Non-goals (don't propose these)
- Not a framework or library for direct production use—designed as a reference implementation and learning resource for understanding design patterns in Go
- Does not provide real-world configuration management, logging, or error handling patterns—focuses on core design pattern structure
- Not a performance comparison tool—implementations prioritize clarity over optimization benchmarks
- Does not cover Go concurrency patterns specifically (goroutines, channels, mutexes) as distinct patterns—focuses on Gang of Four design patterns
- Not a pattern decision guide or project template generator—reference implementation only without scaffolding tools
🪤Traps & gotchas
None identified from file structure. This is a reference library with no external dependencies, environment variables, or runtime services. All patterns are self-contained and work with Go 1.x stdlib. Ensure Go version supports the patterns (most are compatible with Go 1.0+, but 03_singleton uses sync.Once which has been stable since early Go).
🏗️Architecture
💡Concepts to learn
- Interface-based polymorphism in Go — Go replaces inheritance with interface satisfaction—core to how every pattern in this repo adapts classical OOP designs to Go without class hierarchies
- Struct embedding and composition — Go's alternative to inheritance used throughout patterns like Adapter and Proxy—essential for understanding how Go achieves code reuse without deep class trees
- Goroutines and channels for concurrency — Go's concurrency model replaces traditional thread pools and callbacks in patterns like Observer and Mediator—critical for understanding idiomatic Go implementations
- Functional options pattern — Shown in Builder examples—Go idiom for flexible object configuration that replaces telescoping constructors and setter chains from OOP patterns
- sync.Once for singleton initialization — Go's thread-safe initialization primitive in
03_singleton—elegant solution to double-checked locking complexity in classical singleton implementations - Method receiver types (value vs. pointer) — Affects mutability and aliasing semantics in Go patterns—subtle but important for correctly implementing stateful patterns like Prototype and Memento
- Type assertions and interface{} (empty interface) — Used in patterns like Iterator and Composite to handle heterogeneous types in Go—necessary for understanding generic-like behavior before Go generics
🔗Related repos
tmrts/go-patterns— Parallel Go design patterns reference with focus on concurrency patterns and idiomatic Go—complements this repo with goroutine and channel patternsuber-go/guide— Uber's Go style guide with patterns and best practices—provides broader context for when and how to apply these patterns idiomatically in production codegolang-standards/project-layout— Reference for structuring larger Go projects—useful for understanding how design patterns scale beyond single-package examples
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive README.md files for missing pattern directories
Several pattern directories lack README.md files (06_builder, 12_iterator, 13_composite, 19_interpreter), while others have them. Consistency is critical for an educational design pattern repository. READMEs should explain the pattern's intent, when to use it, and walk through the Go implementation in each directory.
- [ ] Create 06_builder/README.md explaining Builder pattern with Go-specific idioms
- [ ] Create 12_iterator/README.md documenting Iterator pattern implementation
- [ ] Create 13_composite/README.md with Composite pattern explanation and Go examples
- [ ] Create 19_interpreter/README.md covering Interpreter pattern concepts
- [ ] Ensure each README follows the same structure as existing ones (01_facade, 02_adapter, etc.)
- [ ] Include code snippets referencing the corresponding .go files in each README
Add integration tests demonstrating pattern interactions across multiple patterns
Current test files (*_test.go) appear to test individual patterns in isolation. Adding a top-level integration test suite would demonstrate how patterns compose together in real-world scenarios, providing significant educational value for learners understanding when/how to combine patterns.
- [ ] Create integration_test.go or tests/ directory at repository root
- [ ] Add test demonstrating Factory Method + Singleton pattern composition
- [ ] Add test combining Strategy + Observer patterns for real-world scenario
- [ ] Add test integrating Builder + Proxy patterns for complex object creation
- [ ] Document in root README.md why these pattern combinations are valuable
Add missing unit test for 19_interpreter/interpreter.go
The file structure shows 19_interpreter/interpreter.go exists but 19_interpreter/interpreter_test.go is absent, breaking consistency with all other 18 patterns that have complete test coverage. This is a straightforward gap in test coverage for a concrete implementation file.
- [ ] Create 19_interpreter/interpreter_test.go following the pattern of existing test files (e.g., 18_flyweight/flyweight_test.go)
- [ ] Write unit tests covering the main interpreter components and expression evaluation
- [ ] Ensure test cases validate the grammar parsing and interpretation logic
- [ ] Run all tests locally with
go test ./...to verify integration - [ ] Update .travis.yml if needed to confirm interpreter tests run in CI
🌿Good first issues
- Add concurrency examples to
03_singleton/singleton_test.godemonstrating thread-safety with multiple goroutines spawning instances—existing tests don't show concurrent race conditions. - Extend
10_observer/README.mdwith a comparison section showing how observer differs from Go channels and when to use each pattern for event-driven systems. - Create benchmarks for factory patterns (
00_simple_factory,04_factory_method,05_abstract_factory) to document performance tradeoffs of each approach in*_test.gofiles.
⭐Top contributors
Click to expand
Top contributors
- @senghoo — 45 commits
- @NightOwlDev007 — 2 commits
- @pomo — 2 commits
- @razertory — 2 commits
- @biwentao — 1 commits
📝Recent commits
Click to expand
Recent commits
e9d687a— Merge pull request #27 from 467892746/fix-wrap (senghoo)6e1ffe1— Merge pull request #26 from pemako/master (senghoo)156a437— fix: wrap (biwentao)070e1fa— format code (NightOwlDev007)ea1f5b3— format code (NightOwlDev007)4c03513— fix typo (#24) (A11Might)62a2f1e— fix: fix some typos (kongtianyi)d382010— update singleton (fgksgf)617f418— fix prototype (denghuaguang)8b065d3— fix typo (senghoo)
🔒Security observations
This repository is a design pattern reference implementation with no direct security vulnerabilities detected in the visible structure. However, the security posture could be improved by: (1) confirming Go module files exist and are properly managed, (2) integrating security scanning into CI/CD (gosec), (3) documenting security considerations for pattern usage, and (4) reviewing the Travis CI configuration for credential leaks. As this is educational code, it should emphasize secure implementation practices in its documentation.
- Low · No Go Module Management Visible —
Repository root. The repository does not show a go.mod or go.sum file in the provided file structure. This makes dependency management and version pinning unclear, potentially leading to unexpected behavior from transitive dependencies. Fix: Ensure go.mod and go.sum files are present and committed to version control. Use 'go mod tidy' to manage dependencies properly and lock versions. - Low · No Security Configuration Baseline —
Repository root. This is a design pattern reference implementation repository. There are no apparent security configuration files, security policies, or SECURITY.md documentation to guide users on secure usage of the patterns. Fix: Add a SECURITY.md file documenting any security considerations when implementing these design patterns in production code. - Low · Limited CI/CD Security Context —
.travis.yml. The .travis.yml file is present but its contents are not provided for review. Travis CI configurations can expose secrets or insecure build practices if misconfigured. Fix: Review .travis.yml to ensure: (1) No secrets are hardcoded, (2) Encrypted environment variables are used for sensitive data, (3) Security scanning tools (gosec, staticcheck) are integrated into the CI pipeline. - Low · No Input Validation Documentation —
Individual pattern README files. The design pattern implementations may be used as templates for production code. Without explicit security guidance in READMEs, developers might implement these patterns without proper input validation and sanitization. Fix: Add security notes to each pattern's README.md explaining security considerations and best practices (e.g., validate inputs, sanitize outputs, use appropriate error handling).
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.