博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go Object Oriented Design
阅读量:7067 次
发布时间:2019-06-28

本文共 10149 字,大约阅读时间需要 33 分钟。

  hot3.png

Go hastypes and valuesrather than classes and objects. So can a language without classes or objects be object-oriented?

While Go may not fit the typical mold of an OOP language, it does  provide many of the same features, albeit in a slightly different way:

  • methodson any typewe define, with no boxing or unboxing

  • automatic message delegation viaembedding

  • polymorphism viainterfaces

  • namespacing viaexports

There is in Go, so leave those is-a relationships at the door. To write Go, we need to think about OO design in terms of composition.

"Use of classical inheritance is always optional; every problem that it solves can be solved another way." -

Composition by Example

Having recently through , I decided to the examples to Go.

Chapter 6 presents a simple problem. A mechanic needs to know which  spare parts to bring on a bike trip, depending on which bikes have been  rented. The problem can be solved using classical inheritance, where MountainBike and RoadBike are specializations of a Bicycle base class. Chapter 8 reworks the same example touse composition instead. I'm quite happy with how well this version . Let's take a look.

Packages

package main import "fmt"

Packages provide a namespace. The main() function of the main package is where a program begins. The fmt package provides string formatting functions.

Types

type Part struct {         Name        string         Description string         NeedsSpare  bool }

We define a new type named Part. This structure is very much like a C struct.

type Parts []Part

The Parts type is a slice of Part values. Slices are variable-length arrays, which are more common in Go than their fixed-length brethren.

Methods

We can declare methods on any user-defined type, so Parts can haveall the behavior of slices, plus our own custom behavior.

func (parts Parts) Spares() (spares Parts) {         for _, part := range parts {                 if part.NeedsSpare {                         spares = append(spares, part)                 }    }    return spares }

A method declaration in Go is just like a function, except it has anexplicit receiver, declared immediately after func. This function also takes advantage of named return variables, pre-initializing spares for us.

The method body is fairly straightforward. We iterate over parts, ignoring the index position (_), filtering the parts to return. The append may need to allocate and return a larger slice, as we didn't preallocate its capacity.

This code isn't nearly as elegant as select in Ruby. A functional filter , but it isn't .

Embedding

type Bicycle struct {         Size string         Parts }

Bicycle is composed of a Size and Parts. By not specifying a named field for Parts, we make use of . This provides automatic delegation with no further ceremony, eg. bike.Spares() and bike.Parts.Spares() are equivalent.

If we were to add a Spares() method to Bicycle, it would take precedence, but we could still reference the embedded Parts.Spares(). This may feel like inheritance, butembedding does not provide polymorphism.The receiver for methods on Parts will always be of type Parts, even when delegated through Bicycle.

Patterns used with classical inheritance, like the template method  pattern, aren't suitable for embedding. It's far better to think in  terms of composition & delegation, as we have here.

Composite Literals

var (     RoadBikeParts = Parts{         {"chain", "10-speed", true},          {"tire_size", "23", true},         {"tape_color", "red", true},     }     MountainBikeParts = Parts{         {"chain", "10-speed", true},         {"tire_size", "2.1", true},         {"front_shock", "Manitou", false},         {"rear_shock", "Fox", true},     }     RecumbentBikeParts = Parts{         {"chain", "9-speed", true},         {"tire_size", "28", true},         {"flag", "tall and orange", true},     } )

Go provides a nice syntax for initializing values, called . Being able to initialize a struct with an array-like syntax made the PartsFactory from the Ruby example feel unnecessary.

func main() {     roadBike := Bicycle{Size: "L", Parts: RoadBikeParts}     mountainBike := Bicycle{Size: "L", Parts: MountainBikeParts}     recumbentBike := Bicycle{Size: "L", Parts: RecumbentBikeParts}

Composite literals can also use a field: value syntax, in which all fields are optional.

The short declaration operator (:=) usestype inferenceto initialize roadBike, etc. with the Bicycle type.

Output

    fmt.Println(roadBike.Spares())    fmt.Println(mountainBike.Spares())    fmt.Println(recumbentBike.Spares())

We print the the result of calling Spares in the default format:

 [{chain 10-speed true} {tire_size 23 true} {tape_color red true}] [{chain 10-speed true} {tire_size 2.1 true} {rear_shock Fox true}] [{chain 9-speed true} {tire_size 28 true} {flag tall and orange true}]

Combining Parts

     comboParts := Parts{}     comboParts = append(comboParts, mountainBike.Parts...)     comboParts = append(comboParts, roadBike.Parts...)     comboParts = append(comboParts, recumbentBike.Parts...)     fmt.Println(len(comboParts), comboParts[9:])     fmt.Println(comboParts.Spares()) }

Parts behaves like a slice. Getting the length, slicing the slice, or combining multiple slices all works as usual.

It would seem that the equivalent solution in Ruby is to subclass  Array, but unfortunately Ruby "misplaces" the spares method when two  Parts are concatenated (update: Steve Klabnik ).

"...in a perfect object-oriented language this solution would be  exactly correct. Unfortunately, the Ruby language has not quite achieved  perfection..." -

Interfaces

Polymorphism in Go is provided by interfaces. They aresatisfied implicitly, unlike Java or C#, so interfaces can be defined for code we don't own.

Compared to duck typing,interfaces are statically checkedand documented through their declaration, rather than through writing a series of respond_to? tests.

"It is impossible to create an abstraction unknowingly or by accident; in statically typed languages defining an interface is always intentional." -

For a simple example, let's say we didn't want to print the NeedsSpare flag of Part. We could write a String method as such:

 func (part Part) String() string {     return fmt.Sprintf("%s: %s", part.Name, part.Description) }

Then the calls to Println above would output this instead:

 [chain: 10-speed tire_size: 23 tape_color: red] [chain: 10-speed tire_size: 2.1 rear_shock: Fox] [chain: 9-speed tire_size: 28 flag: tall and orange]

This works because we have satisfied the Stringer interface, which the fmt package makes use of. It is defined as:

 type Stringer interface {     String() string }

Interface types can be used in the same places as other types.  Variables and arguments can take a Stringer, which accepts anything that  implements the String() string method signature.

Exports

Go uses packages for namespacing. Exported identifiers begin with a  capital letter. To make an identifier internal to a package, we start it  with a lowercase letter:

 type Part struct {     name        string     description string     needsSpare  bool }

Then we could export setter and getter methods:

 func (part Part) Name() string {     return part.name } func (part *Part) SetName(name string) {     part.name = name }

It's easy to determine what is using the public API vs. internal  fields or methods. Just look at the case of the identifier (eg. part.Name() vs. part.name).

Notice that we don't prefix with Get (eg. GetName).  Getters aren't strictly necessary either, especially with strings. When  the need arises, we can always change the Name field to use a custom  type that satisfies the Stringer interface.

Finding Some Privacy

Internal names (lowerCase) can be accessed from anywhere  in the same package, even if the package contains multiple structs  across multiple files. If you find this unsettling, packages can also be  as small as you need.

It is good practice to use the (more stable) public API when possible, even from within the same class in classical languages. Go's use of capitalization makes it easy to see where this is the case.

For Great GOOD

Composition, embedding and interfaces provide powerful tools for Object-Oriented Design in Go.

While Idiomatic Go requires a change in thinking, I am pleasantly  surprised with how simple and concise Go code can be when playing to its  strengths.

Comment on , , , , or the .

"So few people realize that classes and inheritance are mostly  historic accidents and not real needs for good OOD." - Javier Guerra via  Go+

"This is excellent stuff. It helps who looks for correspondences at  least to get started. Some people will inevitably look for OO analogies  when learning Go (like I did!), but the official docs avoid them like  the plague." - Rodrigo Moraes via Go+

"Seconding +Rodrigo Moraes here, excellent stuff. I think this would  have accelerated my own learning curve, where I've kept looking for  classical OO approaches. Thanks for the writeup." - Levi Cook via Go+  and

"Great article, really enjoyed it! Well structured and example code  seems to be good. Will be going over this again tomorrow and adding some  of the tricks I wasn't aware of to my toolbox." - codygman via

"This article was great. I come from the land of C#(and Python, js)  and this really cleared up a lot of questions I had about how OO works  in Go." - TinyGoats via reddit

"Great post! Having also read POODR, it's great to see how well Go  fares in terms of concise-ness and expressiveness against a language  like ruby." - Benjamin Moss via LinkedIn

"Yes, indeed, good post" - Alexander Zhaunerchyk via LinkedIn

"Enjoyed this one. Still trying to wrap my head around some of it." - Sammy Moshe via LinkedIn

"A great introduction to the Go language from : "Go Object Oriented Design" - Pat Shaughnessy via

"There is an awesome article written by Nathan Youngman which I  highly recommend every beginner should read. It really put many details  into perspective for me." - Alejandro Gaviria via

"Your article is a great introduction to Go. I sure could have  benefited from reading it before throwing myself in!" - Andrew  Mackenzie-Ross via

转载于:https://my.oschina.net/jerikc/blog/341429

你可能感兴趣的文章
关于逻辑运算符书写效率问题 和数组 处理问题
查看>>
Performing a full database disaster recovery with RMAN
查看>>
Linux在本地使用yum安装软件(转)
查看>>
第5章 字符串----判断字符串是否相等
查看>>
javascript中遇到的字符串对象处理
查看>>
PHP GD 生成图片验证码+session获取储存验证码
查看>>
【web开发学习笔记】Structs2 Result学习笔记(一)简介
查看>>
android studio中取消关联git
查看>>
Mysql的共享锁和排他锁(转载)
查看>>
Effective C++--经验条款
查看>>
vue 项目中 自定义 webpack 的 配置文件(webpack.config.babel.js)
查看>>
考虑使用jruby
查看>>
深挖洞,广积粮,不称霸
查看>>
执行计划组件、组件、老化
查看>>
分享几个Tooltips插件
查看>>
初探Object Pascal的类(一)
查看>>
Android RenderScript 的使用基础篇
查看>>
MyEclipse6.0.1中SSH项目的配置 (转)
查看>>
HDOJ-1399 Starship Hakodate-maru
查看>>
Android系统Intent中的Uri使用
查看>>