I came across this series of blogposts by Svetlin Ralchev illustrating various design patterns implemented in Go and found it very helpful. Thought you all might enjoy it, too.
评论:
jerf:
gruey:I recall seeing another attempt to port design patterns into Go that was far, far worse than this. However, this still suffers from what I would consider to be excessively slavish dedication to the original format of the design patterns. The original design patterns book was written for C++, and even then was somewhat poorly ported into Scheme, a language that has rather different design patterns. In my opinion, you're much better off describing just the problem, skipping the original diagram entirely which is overcomplicated for Go (and almost every other language that isn't C++ or Java, honestly), and then showing the solution, rather than trying to match the diagram.
For instance, in the Factory Method, all of the factories are attached to
type WhateverFactory struct {}
types, when they should just be functions. If you need a function that takes some input and decides what shape to return dynamically, you don't need the complicated machinery in the official Design Pattern, you needtype Shape interface { ... }
andCreateShape(arguments...) Shape
.The decorator pattern as described is correct, but the description is greatly overcomplicated by the attempt to fit it into the structure of the design patterns of a different language; since Go basically natively implements decoration it's just a way of declaring
type Something interface {}
and making it so that atype Decoration struct { inner Something }
provides an overriding implementation of whatever the Something interface does. (Or possiblytype Decoration struct { Something }
, depending.)And I'm going to say it a second way to be clear; my objection is not to the general idea of documenting useful Go design patterns. It is certainly a language that has design patterns. My objection is using diagrams and concepts used for C++ and trying to jam them into Go, rather than simply discussing the problem and then the Go-native solutions. You will also miss out on design patterns specific to Go, such as ways you can use channels. Even if you're trying to educate someone very versed in the C++ design patterns in question, you're still better off going straight to problem and Go-native solution.
schumacherfm:This is basically describes a problem I see fairly often in practice: people impliment a design pattern and lose sight of the problem they are solving. You often end up with an overcomplicated, hard to understand mess instead of an elegant solution designed for maintainability.
geodel:This is then called "Enterprise Software" ;-(
For my purpose Enterprise software like Spring provides endless supply of lovely class/method/variable names.
