[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n*.prof\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: go\n\ngo:\n  - 1.6\n\ninstall:\n  - go get golang.org/x/tools/cmd/cover\n  - go get github.com/mattn/goveralls\n\nscript:\n  - go build  github.com/BPing/golang_design_pattern/pattern\n\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# golang_design_pattern\nCode to achieve the design model with golang \n\n [![Stargazers over time](https://starcharts.herokuapp.com/BPing/golang_design_pattern.svg)](https://starcharts.herokuapp.com/BPing/golang_design_pattern)\n\n# 设计模式\n用golang语言实现设计模式\n\n# 设计模式的六大原则\n\n摘自 [Java开发中的23种设计模式详解](http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html)\n \n * 1、开闭原则（Open Close Principle）\n \n    开闭原则就是说对扩展开放，对修改关闭。在程序需要进行拓展的时候，不能去修改原有的代码，实现一个热插拔的效果。\n    所以一句话概括就是：为了使程序的扩展性好，易于维护和升级。想要达到这样的效果，我们需要使用接口和抽象类，后\n    面的具体设计中我们会提到这点。\n \n * 2、里氏代换原则（Liskov Substitution Principle）\n \n    里氏代换原则(Liskov Substitution Principle LSP)面向对象设计的基本原则之一。 里氏代换原则中说，任何\n    基类可以出现的地方，子类一定可以出现。 LSP是继承复用的基石，只有当衍生类可以替换掉基类，软件单位的功能不受\n    到影响时，基类才能真正被复用，而衍生类也能够在基类的基础上增加新的行为。里氏代换原则是对“开-闭”原则的补充。\n    实现“开-闭”原则的关键步骤就是抽象化。而基类与子类的继承关系就是抽象化的具体实现，所以里氏代换原则是对实现抽\n    象化的具体步骤的规范。—— From Baidu 百科\n \n * 3、依赖倒转原则（Dependence Inversion Principle）\n \n    这个是开闭原则的基础，具体内容：真对接口编程，依赖于抽象而不依赖于具体。\n \n * 4、接口隔离原则（Interface Segregation Principle）\n \n    这个原则的意思是：使用多个隔离的接口，比使用单个接口要好。还是一个降低类之间的耦合度的意思，从这儿我们看出，\n    其实设计模式就是一个软件的设计思想，从大型软件架构出发，为了升级和维护方便。所以上文中多次出现：降低依赖，降低耦合。\n \n * 5、迪米特法则（最少知道原则）（Demeter Principle）\n \n    为什么叫最少知道原则，就是说：一个实体应当尽量少的与其他实体之间发生相互作用，使得系统功能模块相对独立。\n \n * 6、合成复用原则（Composite Reuse Principle）\n \n    原则是尽量使用合成/聚合的方式，而不是使用继承。\n\n# 文档\nhttps://godoc.org/github.com/BPing/golang_design_pattern/pattern [![GoDoc](https://godoc.org/github.com/BPing/golang_design_pattern/pattern?status.svg)](https://godoc.org/github.com/BPing/golang_design_pattern/pattern)\n\n# 同类项目（golang）\n [go-pattern](https://github.com/tmrts/go-patterns)\n \n\n \n\n\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"github.com/BPing/golang_design_pattern/pattern\"\n)\n\nfunc main() {\n\n\tvar battery pattern.RechargeableBattery\n\n\tbattery = pattern.AdapterNonToYes{pattern.NonRechargeableA{}}\n\tbattery.Use()\n\tbattery.Charge()\n\n\tbattery = pattern.NonRechargeableB{}\n\tbattery.Use()\n\tbattery.Charge()\n\n}\n"
  },
  {
    "path": "pattern/AbstractFactory.go",
    "content": "package pattern\n\n\n//抽象工厂\ntype AbstractFactory interface {\n\tProduce() pen //生产笔\n}\n\ntype PencilFactory struct {\n}\n\nfunc (PencilFactory) Produce() pen {\n\treturn new(pencil)\n}\n\ntype BrushPen struct {\n}\n\nfunc (BrushPen) Produce() pen {\n\treturn new(brushPen)\n}\n"
  },
  {
    "path": "pattern/Adapter.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n//\n// 适配器模式\n//    是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式，它结合了两个独立接口的功能。\n//    或者\n//    将一个类的接口转换成客户希望的另外一个接口。\n//    Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。\n//\n//   主要分为三类：类的适配器模式、对象的适配器模式、接口的适配器模式\n//\n\n//不可充电电池使用接口\ntype NonRechargeableBattery interface {\n\tUse()\n}\n\n//可充电电池使用接口\ntype RechargeableBattery interface {\n\tUse()\n\tCharge()\n}\n\n//不可充电电池A\ntype NonRechargeableA struct {\n}\n\nfunc (NonRechargeableA) Use() {\n\tfmt.Println(\"NonRechargeableA using \")\n}\n\n//类的适配器模式\n// 似乎golang语言层面已经支持了，暂且搁置\n//\n//\n\n//对象的适配器模式\n\n//适配可充电电池使用接口\ntype AdapterNonToYes struct {\n\tNonRechargeableBattery\n}\n\nfunc (AdapterNonToYes) Charge() {\n\tfmt.Println(\"AdapterNonToYes Charging\")\n\t//nothing to do ,just adapt for RechargeableBattery's interface\n}\n\n//接口的适配器模式\n\ntype RechargeableBatteryAbstract struct {\n}\n\nfunc (RechargeableBatteryAbstract) Use() {\n\tfmt.Println(\"RechargeableBatteryAbstract using\")\n}\nfunc (RechargeableBatteryAbstract) Charge() {\n\tfmt.Println(\"RechargeableBatteryAbstract Charging\")\n}\n\ntype NonRechargeableB struct {\n\tRechargeableBatteryAbstract\n}\n\nfunc (NonRechargeableB) Use() {\n\tfmt.Println(\"NonRechargeableB using \")\n}\n\n//test\nfunc AdapterTest() {\n\tvar battery RechargeableBattery\n\n\tbattery = AdapterNonToYes{NonRechargeableA{}}\n\tbattery.Use()\n\tbattery.Charge()\n\n\tbattery = NonRechargeableB{}\n\tbattery.Use()\n\tbattery.Charge()\n}\n"
  },
  {
    "path": "pattern/Bridge.go",
    "content": "package pattern\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n//\n// 桥接模式\n//    是用于把抽象化与实现化解耦，使得二者可以独立变化。这种类型的设计模式属于结构型模式，\n//    它通过提供抽象化和实现化之间的桥接结构，来实现二者的解耦。\n//\n\n//请求接口\ntype Request interface {\n\tHttpRequest() (*http.Request, error)\n}\n\n//客户端\ntype Client struct {\n\tClient *http.Client\n}\n\nfunc (c *Client) Query(req Request) (resp *http.Response, err error) {\n\thttpreq,_:=req.HttpRequest()\n\tresp, err = c.Client.Do(httpreq)\n\treturn\n}\n\ntype CdnRequest struct {\n}\n\nfunc (cdn *CdnRequest) HttpRequest() (*http.Request,  error) {\n\treturn http.NewRequest(\"GET\", \"/cdn\", nil)\n}\n\ntype LiveRequest struct {\n}\n\nfunc (cdn *LiveRequest) HttpRequest() (*http.Request, error) {\n\treturn http.NewRequest(\"GET\", \"/live\", nil)\n}\n\nfunc TestBridge() {\n\tclient := &Client{http.DefaultClient}\n\n\tcdnReq := &CdnRequest{}\n\tfmt.Println(client.Query(cdnReq))\n\n\tliveReq := &LiveRequest{}\n\tfmt.Println(client.Query(liveReq))\n}\n"
  },
  {
    "path": "pattern/Builder.go",
    "content": "package pattern\n\nconst (\n\tFOOD  = \"food\"\n\tDRINK = \"drink\"\n)\n\ntype Item interface {\n\tPrice() float32   //价钱\n\tName() string     //名称\n\tCategory() string //类别\n}\n\n//食物\ntype Food struct {\n}\n\nfunc (Food) Price() float32 {\n\treturn 0.0\n}\nfunc (Food) Name() string {\n\treturn \"\"\n}\nfunc (Food) Category() string {\n\treturn FOOD\n}\n\n//饮料\ntype Drink struct {\n}\n\nfunc (Drink) Price() float32 {\n\treturn 0.0\n}\nfunc (Drink) Name() string {\n\treturn \"\"\n}\nfunc (Drink) Category() string {\n\treturn DRINK\n}\n\n//汉堡\ntype Hamburger struct {\n\tFood\n}\n\nfunc (Hamburger) Price() float32 {\n\treturn 12.00\n}\nfunc (Hamburger) Name() string {\n\treturn \"Hamburger\"\n}\n\n//炸鸡\ntype FriedChicken struct {\n\tFood\n}\n\nfunc (FriedChicken) Price() float32 {\n\treturn 18.00\n}\nfunc (FriedChicken) Name() string {\n\treturn \"FriedChicken\"\n}\n\n//可乐\ntype Cola struct {\n\tDrink\n}\n\nfunc (Cola) Price() float32 {\n\treturn 3.00\n}\nfunc (Cola) Name() string {\n\treturn \"Cola\"\n}\n\n//啤酒\ntype Beer struct {\n\tDrink\n}\n\nfunc (Beer) Price() float32 {\n\treturn 5.00\n}\nfunc (Beer) Name() string {\n\treturn \"Beer\"\n}\n\ntype Meal []Item\n\nfunc (this *Meal) AddItem(item ...Item) {\n\t*this = append(*this, item...)\n}\n\nfunc (this Meal) GetCost() (cost float32) {\n\tfor _, val := range this {\n\t\tcost += val.Price()\n\t}\n\treturn\n}\nfunc (this Meal) ShowItems() (msg string) {\n\tfor _, val := range this {\n\t\tmsg += \"Category：\" + val.Category() + \" Name:\" + val.Name() + \"\\n\"\n\t}\n\treturn\n}\n\n//建造者\ntype MealBuilder struct {\n}\n\nfunc (MealBuilder) MealOne() (meal *Meal) {\n\tmeal = new(Meal)\n\tmeal.AddItem(new(FriedChicken), new(Beer))\n\treturn\n}\n"
  },
  {
    "path": "pattern/ChainOfResponsibility.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n// 责任链模式\n//      使多个对象都有机会处理请求，从而避免请求的发送者和接收者之间的耦合关系。\n//      将这些对象连成一条链，并沿着这条链传递该请求，直到有一个对象处理它为止。\n//\n//    github.com/BPing/Golib/middleware 包就是基于此模式实现的\n\n\ntype ScreenEvent struct {\n\tType string\n\tComment string\n}\n\ntype IScreenEventHandler interface{\n\tHandle(*ScreenEvent)bool\n\tSetNextHandler(IScreenEventHandler)\n}\n\ntype AbsScreenEventHandler struct {\n\tNextHandler IScreenEventHandler\n}\n\nfunc(ase *AbsScreenEventHandler)Handle(se *ScreenEvent)bool{\n\tif ase.NextHandler!=nil {\n\t\treturn ase.NextHandler.Handle(se)\n\t}\n\treturn false\n}\n\nfunc(ase *AbsScreenEventHandler)SetNextHandler(ise IScreenEventHandler){\n\tase.NextHandler=ise\n}\n\ntype HomeScreenEventHandler  struct {\n\tAbsScreenEventHandler\n}\n\nfunc(hse *HomeScreenEventHandler)Handle(se *ScreenEvent)bool{\n\tfmt.Println(\"HomeScreenEventHandler.....\")\n\tif se.Type==\"HomeClick\" {\n\t\tfmt.Println(\"HomeClick\")\n\t\treturn true\n\t}\n\treturn hse.AbsScreenEventHandler.Handle(se)\n}\n\ntype UserScreenEventHandler  struct {\n\tAbsScreenEventHandler\n}\n\nfunc(use *UserScreenEventHandler)Handle(se *ScreenEvent)bool{\n\tfmt.Println(\"UserScreenEventHandler.....\")\n\tif se.Type==\"UserModelClick\" {\n\t\tfmt.Println(\"UserModelClick\")\n\t\treturn true\n\t}\n\treturn use.AbsScreenEventHandler.Handle(se)\n}\n\nfunc ChainOfResponsibilityTest(){\n\t  var osd IScreenEventHandler\n\t   osd=&AbsScreenEventHandler{}\n\t   home:=&HomeScreenEventHandler{}\n\t   user:=&UserScreenEventHandler{}\n\t   home.SetNextHandler(user)\n\t   osd.SetNextHandler(home)\n\n\tscreenEvent:=&ScreenEvent{Type:\"HomeClick\"}\n\tosd.Handle(screenEvent)\n\n\tfmt.Println(\"-----------------------------------------------\\n\")\n\tscreenEvent=&ScreenEvent{Type:\"UserModelClick\"}\n\tosd.Handle(screenEvent)\n\n\tfmt.Println(\"-----------------------------------------------\\n\")\n\tscreenEvent=&ScreenEvent{Type:\"Null\"}\n\tosd.Handle(screenEvent)\n}"
  },
  {
    "path": "pattern/Command.go",
    "content": "package pattern\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n// Command（命令）\n//  命令模式（Command Pattern）是一种数据驱动的设计模式，它属于行为型模式。\n//  请求以命令的形式包裹在对象中，并传给调用对象。 调用对象寻找可以处理该命令\n//  的合适的对象，并把该命令传给相应的对象，该对象执行命令。\n//\n\n// 命令接口\ntype Command interface {\n\tDo(args interface{}) (interface{}, error)\n}\n\n// Get 命令\ntype GetCommand struct {\n}\n\nfunc (gc *GetCommand) Do(args interface{}) (interface{}, error) {\n\tfmt.Println(\"GetCommand\")\n\treturn args, nil\n}\n\n// post 命令\ntype PostCommand struct {\n}\n\nfunc (pc *PostCommand) Do(args interface{}) (interface{}, error) {\n\tfmt.Println(\"PostCommand\")\n\treturn args, nil\n}\n\n// 上下文\ntype CmdContext struct {\n\tCmdType string\n\tArgs    interface{}\n}\n\n// 命令管理者\ntype CommandHandler struct {\n\tCmdMap map[string]Command\n}\n\n// 处理命令\nfunc (ch *CommandHandler) Handle(ctx *CmdContext) (interface{}, error) {\n\tif ctx == nil {\n\t\treturn nil, errors.New(\"\")\n\t}\n\tcmd, ok := ch.CmdMap[ctx.CmdType]\n\tif ok {\n\t\treturn cmd.Do(ctx.Args)\n\t}\n\treturn nil, errors.New(\"invalid Command \")\n}\n\n// 注册命令\nfunc (ch *CommandHandler) Register(cmdType string, cmd Command) {\n\tch.CmdMap[cmdType] = cmd\n}\n\n//\nfunc CommandTest() {\n\tcmdHandler := &CommandHandler{CmdMap: make(map[string]Command)}\n\tpostCtx := &CmdContext{CmdType: \"post\", Args: \" Post\"}\n\tgetCtx := &CmdContext{CmdType: \"get\", Args: \" Get\"}\n\tnullCtx := &CmdContext{CmdType: \"null\", Args: \" Get\"}\n\tcmdHandler.Register(\"post\", &PostCommand{})\n\tcmdHandler.Register(\"get\", &GetCommand{})\n\n\tfmt.Println(cmdHandler.Handle(postCtx))\n\tfmt.Println(cmdHandler.Handle(getCtx))\n\tfmt.Println(cmdHandler.Handle(nullCtx))\n\n}\n"
  },
  {
    "path": "pattern/Composite.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n//\n// 组合模式 将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。\n//\n\ntype Department struct {\n\tList   map[string]*Department\n\tParent *Department\n\tName   string\n\tId     string\n}\n\n// 批量添加子节点\nfunc (this *Department) Add(departments ...*Department) {\n\tfor _, department := range departments {\n\t\tdepartment.AddTo(this)\n\t}\n}\n\n// 添加到对应的父节点\nfunc (this *Department) AddTo(parent *Department) {\n\tthis.Parent = parent\n\tparent.add(this)\n}\n\n// 添加子节点\nfunc (this *Department) add(department *Department) {\n\tthis.List[department.Id] = department\n}\n\n// 查找子节点\nfunc (this *Department) Find(id string) (department *Department) {\n\tdepartment, ok := this.List[id]\n\tif !ok {\n\t\tfor _, de := range this.List {\n\t\t\tdepartment = de.Find(id)\n\t\t\tif nil != department {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\treturn\n}\n\n// 移除子节点\nfunc (this *Department) Remove(id string) (department *Department) {\n\tdepartment, ok := this.List[id]\n\tif !ok {\n\t\tfor _, de := range this.List {\n\t\t\tdepartment = de.Remove(id)\n\t\t\tif nil != department {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tdelete(this.List, id)\n\treturn\n}\n\n// 遍历\nfunc (this *Department) ReadList() {\n\tfmt.Printf(\"Node :%s(%s) \\n the  children: \\n\", this.Id, this.Name)\n\tfor _, de := range this.List {\n\t\tde.ReadList()\n\t}\n}\n\n// example\nfunc CompositeTest() {\n\troot := &Department{Name: \"root\", Id: \"0010\"}\n\tchildren1 := &Department{Name: \"network\", Id: \"00010\"}\n\tchildren2 := &Department{Name: \"forward\", Id: \"00011\"}\n\troot.Add(children1, children2)\n\tchildren1.Add(&Department{Name: \"network1\", Id: \"0001010\"})\n\n\troot.Find(\"0001010\").ReadList()\n\n\troot.ReadList()\n\n\troot.Remove(\"00010\").ReadList()\n\n\troot.ReadList()\n\n}\n"
  },
  {
    "path": "pattern/Decorator.go",
    "content": "package pattern\n\nimport (\n\t\"strings\"\n\t\"fmt\"\n\t\"log\"\n)\n\n//\n// 装饰模式\n//    动态地给一个对象添加一些额外的职责，同时又不改变其结构\n//\n\n// 接口\ntype  MessageBuilder interface{\n\t Build(messages ... string) string\n}\n\n// 基本信息构造器\ntype BaseMessageBuilder struct {\n\n}\n\nfunc(b *BaseMessageBuilder)Build(messages ... string) string{\n\treturn strings.Join(messages,\",\")\n}\n\n// 引号装饰器\ntype QuoteMessageBuilderDecorator struct {\n\tBuilder MessageBuilder\n}\n\nfunc(q *QuoteMessageBuilderDecorator)Build(messages ... string) string{\n\treturn \"\\\"\"+q.Builder.Build(messages...)+\"\\\"\"\n}\n\n\n// 大括号装饰器\ntype BraceMessageBuilderDecorator struct {\n\tBuilder MessageBuilder\n}\n\nfunc(b *BraceMessageBuilderDecorator)Build(messages ... string) string{\n\treturn \"{\"+b.Builder.Build(messages...)+\"}\"\n}\n\n\n// 或者\n\n\ntype Object func(int) int\n\nfunc LogDecorate(fn Object) Object {\n\treturn func(n int) int {\n\t\tlog.Println(\"Starting the execution with the integer\", n)\n\n\t\tresult := fn(n)\n\n\t\tlog.Println(\"Execution is completed with the result\", result)\n\n\t\treturn result\n\t}\n}\n\nfunc Double(n int) int {\n\treturn n * 2\n}\n\n\n// 调试\nfunc DecoratorTest(){\n\tvar MB MessageBuilder\n\n\tMB=&BaseMessageBuilder{}\n\n\tfmt.Println(MB.Build(\"hello world\"))\n\n\tMB=&QuoteMessageBuilderDecorator{MB}\n\n\tfmt.Println(MB.Build(\"hello world\"))\n\n\tMB=&BraceMessageBuilderDecorator{MB}\n\n\tfmt.Println(MB.Build(\"hello world\"))\n\n\n\t//\n\tf := LogDecorate(Double)\n\tf(5)\n}"
  },
  {
    "path": "pattern/Facade.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n//\n// 外观模式\n//       隐藏系统的复杂性，并向客户端提供了一个客户端可以访问系统的接口\n//\n\ntype Coder struct {\n}\n\nfunc (c *Coder) Coding() {\n\tfmt.Println(\"Coding ....\")\n}\n\ntype Tester struct {\n}\n\nfunc (t *Tester) Testing() {\n\tfmt.Println(\"Testing ....\")\n}\n\ntype ProductPlanner struct {\n}\n\nfunc (p *ProductPlanner) Planing() {\n\tfmt.Println(\"Planing ....\")\n}\n\ntype MaintenancePeople struct {\n}\n\nfunc (m *MaintenancePeople) Releasing() {\n\tfmt.Println(\"Releasing ....\")\n}\n\n// 公司\n//  拥有产品策划、程序员、测试人员，运维人员\n//  通过公司这个外观对外提供服务，\n//  而不是直接通过某个类型人员对外服务（虽然最终提供服务的也是某个类型的人员）\ntype Company struct {\n\tProductPlanner\n\tCoder\n\tTester\n\tMaintenancePeople\n}\n\n// 对外提供生产产品服务\n// 需要各个类型人员合作，但细节不对外公开的\nfunc (com *Company) Producing() {\n\t// 策划产品\n\tcom.ProductPlanner.Planing()\n\t// 编码实现\n\tcom.Coder.Coding()\n\t// 测试产品\n\tcom.Tester.Testing()\n\t// 发布产品\n\tcom.MaintenancePeople.Releasing()\n\n\t// 或者\n\t//com.Planing()\n\t//com.Coding()\n\t//com.Testing()\n\t//com.Releasing()\n}\n\nfunc FacadeTest() {\n\tcom := &Company{}\n\n\tcom.Producing()\n\n\t// 单独调用某个功能，\n\t// 通过公司外观提供的服务\n\tcom.Testing()\n}\n"
  },
  {
    "path": "pattern/Factory.go",
    "content": "package pattern\n\n//工厂模式适合：凡是出现了大量的产品需要创建，\n//并且具有共同的接口时，可以通过工厂方法模式进行创建\nimport \"fmt\"\n\n//笔\ntype pen interface {\n\t//写字\n\tWrite()\n}\n\ntype pencil struct {\n}\n\nfunc (p *pencil) Write() {\n\tfmt.Println(\"铅笔\")\n}\n\ntype brushPen struct {\n}\n\nfunc (p *brushPen) Write() {\n\tfmt.Println(\"毛笔\")\n}\n\n//工厂\ntype PenFactory struct {\n}\n\nfunc (this PenFactory) Produce(typ string) pen {\n\tswitch typ {\n\tcase \"pencil\":\n\t\treturn this.ProducePencil()\n\tcase \"brush\":\n\t\treturn this.ProduceBrushPen()\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (PenFactory) ProducePencil() pen {\n\treturn new(pencil)\n}\n\nfunc (PenFactory) ProduceBrushPen() pen {\n\treturn new(brushPen)\n}\n"
  },
  {
    "path": "pattern/Flyweight.go",
    "content": "package pattern\n\nimport (\n\t\"fmt\"\n)\n\n//\n// 享元模式\n//    实现对象的共享，即共享池，当系统中对象多的时候可以减少内存的开销，通常与工厂模式一起使用。\n//    sync.pool 就属于此模式\n//\n\n// 数据库连接池\ntype DbConnectPool struct {\n\tConnChan chan *DbConnect\n}\n\nfunc NewDbConnectPool(chanLen int)*DbConnectPool{\n\treturn &DbConnectPool{ConnChan:make(chan *DbConnect,chanLen)}\n}\n\nfunc(dc *DbConnectPool) Get()*DbConnect{\n\tselect {\n\tcase conn := <-dc.ConnChan:\n\t\treturn conn\n\tdefault:\n\t        // 无则新建\n\t\treturn new(DbConnect)\n\t}\n}\nfunc(dc *DbConnectPool) Put(conn *DbConnect){\n\tselect {\n\tcase dc.ConnChan <- conn:\n\t\treturn\n\tdefault:\n\t       // 满则丢弃\n\t\treturn\n\t}\n}\n\n// 数据库连接\ntype DbConnect struct {\n\n}\n\nfunc (*DbConnect) Do(){\n\tfmt.Println(\"connect......doing....\")\n}\n\n\nfunc FlyweightTest(){\n\tpool:=NewDbConnectPool(2)\n\tconn:=pool.Get()\n\tconn.Do()\n\tpool.Put(conn)\n}\n"
  },
  {
    "path": "pattern/Interpreter.go",
    "content": "package pattern\n\nimport (\n\t\"strings\"\n\t\"fmt\"\n)\n\n//解释器模式（Interpreter Pattern）\n//    提供了评估语言的语法或表达式的方式，文法解释，它属于行为型模式。\n// 这种模式实现了一个表达式接口，该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等。\n//\n// 一般递归处理\n\n\n\ntype Expression interface {\n\tInterpret(context string) bool\n}\n\ntype TerminalExpression struct {\n\tWord string\n}\n\n// 终结符\nfunc(te *TerminalExpression)Interpret(context string) bool{\n\tif strings.Contains(context,te.Word) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// 或\ntype OrExpression struct {\n\tA Expression\n\tB Expression\n}\n\nfunc(oe *OrExpression)Interpret(context string) bool{\n\treturn oe.A.Interpret(context)||oe.B.Interpret(context)\n}\n\n// 与\ntype AndExpression  struct {\n\tA Expression\n\tB Expression\n}\n\nfunc(ae *AndExpression )Interpret(context string) bool{\n\treturn ae.A.Interpret(context)&&ae.B.Interpret(context)\n}\n\nfunc InterpreterTest(){\n\tisMale :=&OrExpression{&TerminalExpression{\"Robert\"},&TerminalExpression{\"John\"}}\n\tisMarriedWoman :=&AndExpression{&TerminalExpression{\"Julie\"},&TerminalExpression{\"Married\"}}\n\tfmt.Println(\"John is male?\",isMale.Interpret(\"John\"))\n\tfmt.Println(\"Julie is a married women?\",isMarriedWoman.Interpret(\"Married Julie\"))\n}"
  },
  {
    "path": "pattern/Iterator.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n//\n// 迭代器模式（Iterator Pattern）\n//  这种模式用于顺序访问集合对象的元素，不需要知道集合对象的底层表示。\n\n// 迭代器接口\ntype Iterator interface {\n\tHasNext() bool\n\tNext() interface{}\n}\n\n// 集合接口\ntype Container interface {\n\tGetIterator() Iterator\n}\n\n// 数组迭代器\ntype ArrayIterator struct {\n\tcurrentIndex int\n\tac           *ArrayContainer\n}\n\nfunc (ai *ArrayIterator) HasNext() bool {\n\tif ai.ac.arrayData!=nil&&ai.currentIndex < len(ai.ac.arrayData) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (ai *ArrayIterator) Next() interface{} {\n\tif ai.HasNext() {\n\t\tdefer func() { ai.currentIndex++ }()\n\t\treturn ai.ac.arrayData[ai.currentIndex]\n\n\t}\n\treturn nil\n}\n\n// 数组集合\ntype ArrayContainer struct {\n\tarrayData []interface{}\n}\n\nfunc (ac *ArrayContainer) GetIterator() Iterator {\n\treturn &ArrayIterator{currentIndex: 0, ac: ac}\n}\n\n\nfunc IteratorTest(){\n\tarr:=[]interface{}{\"a\",\"b\",\"c\",\"d\"}\n\tarrayContainer:=&ArrayContainer{arrayData:arr}\n\titerator:=arrayContainer.GetIterator()\n\tfor iterator.HasNext(){\n\t\tfmt.Println(iterator.Next().(string))\n\t}\n}"
  },
  {
    "path": "pattern/Mediator.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n// 中介者模式（Mediator Pattern）\n//     是用来降低多个对象和类之间的通信复杂性。\n//  这种模式提供了一个中介类，该类通常处理不同类之间的通信，并支持松耦合，使代码易于维护\n\n\ntype ChatRoom struct {\n       name string\n}\n\nfunc (cr *ChatRoom)SendMsg(msg string){\n\tfmt.Println(cr.name+\" : \"+msg)\n}\nfunc (cr *ChatRoom)RegisterUser(u *User){\n\tu.cr=cr\n}\n\ntype User struct {\n\tname string\n\tcr *ChatRoom\n}\n\nfunc (u *User)SendMsg(msg string){\n\tif u.cr!=nil {\n\t\tu.cr.SendMsg(u.name+\" : \"+msg)\n\t}\n}\n\nfunc MediatorTest(){\n\tAUser:=&User{name:\"AUser\"}\n\tBUser:=&User{name:\"BUser\"}\n\n\tchatRoom:=&ChatRoom{name:\"chatRoom123456\"}\n\tchatRoom.RegisterUser(AUser)\n\tchatRoom.RegisterUser(BUser)\n\n\tAUser.SendMsg(\"hello AUser\")\n\tBUser.SendMsg(\"hello BUser\")\n\n}\n"
  },
  {
    "path": "pattern/Memento.go",
    "content": "package pattern\n\nimport (\n\t\"container/list\"\n\t\"fmt\"\n)\n\n// 备忘录模式（Memento pattern）\n//   在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态。\n//   这样以后就可将该对象恢复到原先保存的状态。\n\n// 相关模式：原型模式\n\n// 文本编辑\ntype Text struct {\n\tValue string\n}\n\n// 写\nfunc (t *Text) Write(value string) {\n\tt.Value = value\n}\n\n// 读取\nfunc (t *Text) Read() string {\n\treturn t.Value\n}\n\n// 备忘\nfunc (t *Text) SaveToMemento() *Memento {\n\treturn &Memento{Value: t.Value}\n}\n\n// 从备忘恢复\nfunc (t *Text) RestoreFromMemento(m *Memento) {\n\tif m!=nil {\n\t\tt.Value = m.Value\n\t}\n\treturn\n}\n\n// 备忘结构\ntype Memento struct {\n\tValue string\n}\n\n// 管理备忘记录\ntype Storage struct {\n\t*list.List\n}\n\n// Back returns the last element of list l or nil.\n// and remove form list\nfunc (s *Storage)RPop()*list.Element{\n\tele:=s.Back()\n\tif ele!=nil{\n\t\ts.Remove(ele)\n\t}\n\treturn ele\n}\n\n\nfunc MementoTest(){\n        storage:=&Storage{list.New()}\n\ttext:=&Text{\"hello world\"}\n\tfmt.Println(text.Read())\n\tstorage.PushBack(text.SaveToMemento())\n\ttext.Write(\"nihao\")\n\tfmt.Println(text.Read())\n\tstorage.PushBack(text.SaveToMemento())\n\ttext.Write(\"i know\")\n\tfmt.Println(text.Read())\n\n\t//后退回滚\n\tmediator:=storage.RPop()\n\tif mediator!=nil {\n\t\ttext.RestoreFromMemento(mediator.Value.(*Memento))\n\t}\n\tfmt.Println(text.Read())\n\n\t//后退回滚\n\tmediator=storage.RPop()\n\tif mediator!=nil {\n\t\ttext.RestoreFromMemento(mediator.Value.(*Memento))\n\t}\n\tfmt.Println(text.Read())\n\n\t//后退 已没有\n\tmediator=storage.RPop()\n\tif mediator!=nil {\n\t\ttext.RestoreFromMemento(mediator.Value.(*Memento))\n\t}\n\tfmt.Println(text.Read())\n\n}"
  },
  {
    "path": "pattern/Observer.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n//\n// 观察者模式（Observer Pattern）\n//  定义对象间的一种一对多的依赖关系,\n//  当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。\n//\n\ntype Observer interface {\n\tNotify(interface{})\n}\n\ntype Subject struct {\n\tobservers []Observer\n\tstate     string\n}\n\nfunc (s *Subject)SetState(state string) {\n\ts.state = state\n\ts.NotifyAllObservers()\n}\nfunc (s *Subject)Attach(observer ... Observer) {\n\ts.observers = append(s.observers, observer ...)\n}\n\nfunc (s *Subject)NotifyAllObservers() {\n\tfor _, obs := range s.observers {\n\t\tobs.Notify(s)\n\t}\n}\n\ntype AObserver struct {\n\tId string\n}\n\nfunc (ao *AObserver)Notify(sub interface{}) {\n\tfmt.Println(ao.Id , \" receive \", sub.(*Subject).state)\n}\n\nfunc ObserverTest() {\n\tsub := &Subject{}\n\ta := &AObserver{Id:\"A\"}\n\tb := &AObserver{Id:\"b\"}\n\tsub.Attach(a,b)\n\tsub.SetState(\"hello world\")\n\tsub.SetState(\"i know\")\n\n}"
  },
  {
    "path": "pattern/Prototype.go",
    "content": "package pattern\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n//\n// 原型模式\n//  用原型实例指定创建对象的种类，并且通过拷贝这些原型创建新的对象。\n//\n// ps:或者可以使用sync.Pool来替代原型模式方式\n//\n\ntype Cloneable interface {\n\tClone() interface{}\n}\n\ntype Context struct {\n}\n\nfunc (this *Context) Clone() interface{} {\n\tnew_obj := (*this)\n\treturn &new_obj\n}\n\n//结构体基本信息\nfunc (this *Context) string(typ interface{}) (str string) {\n\tv := reflect.ValueOf(typ).Elem()\n\tstr += \"Type:\" + v.Type().Name() + \"\\n\"\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i)\n\t\tstr += fmt.Sprintf(\"index %d: %s %s = %v\\n\", i,\n\t\t\tv.Type().Field(i).Name, f.Type(), f.Interface())\n\t}\n\treturn\n}\n\ntype Context1 struct {\n\tUri string\n\tContext\n}\n\nfunc (this *Context1) SetUri(uri string) {\n\tthis.Uri = uri\n}\n\nfunc (this *Context1) String() (str string) {\n\treturn this.string(this)\n}\n\ntype Context2 struct {\n\tContext\n\tEcho string\n}\n\nfunc (this *Context2) SetEcho(echo string) {\n\tthis.Echo = echo\n}\n\nfunc (this *Context2) String() (str string) {\n\treturn this.string(this)\n}\n\n//原型池\ntype ContextPool map[string]*Context\n\nfunc (this *ContextPool) AddContext(key string, val *Context) {\n\t(*this)[key] = val\n}\n\nfunc (this *ContextPool) GetContext(key string) *Context {\n\tval, ok := (*this)[key]\n\tif ok {\n\t\treturn val.Clone().(*Context)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "pattern/Proxy.go",
    "content": "package pattern\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n// 代理模式\n//     为其他对象提供一种代理以控制对这个对象的访问\n//     优点： 1、职责清晰。 2、高扩展性。 3、智能化。\n//     注意事项：\n//          1、和适配器模式的区别：适配器模式主要改变所考虑对象的接口，\n//             而代理模式不能改变所代理类的接口。\n//          2、和装饰器模式的区别：装饰器模式为了增强功能，而代理模式\n//             是为了加以控制。\n\n\n// 似乎有点像装饰模式\n\ntype Device interface {\n\tRead()([]byte,error)\n\tWrite(word []byte)error\n}\n\ntype HardDisk struct {\n\tstorage []byte\n}\n\nfunc(h *HardDisk)Read()([]byte,error){\n\treturn h.storage,nil\n}\nfunc(h *HardDisk)Write(word []byte)error{\n\th.storage=word\n\treturn nil\n}\n\ntype HardDiskProxy struct {\n\tOpId string\n\thd *HardDisk\n}\n\nfunc(h *HardDiskProxy)Read()([]byte,error){\n\tif !h.permission(\"read\") {\n\t\treturn nil ,errors.New(\"You don't have permission to read\")\n\t}\n\treturn h.hd.Read()\n}\nfunc(h *HardDiskProxy)Write(word []byte)error{\n\tif !h.permission(\"wrire\") {\n\t\treturn errors.New(\"You don't have permission to write\")\n\t}\n\treturn h.hd.Write(word)\n}\n\n// 权限判断\nfunc(h *HardDiskProxy)permission(tag string)bool{\n\tif h.OpId==\"admin\"{\n\t\treturn true\n\t}\n\n\tif h.OpId==\"reader\"&&tag==\"read\"{\n\t\treturn true\n\t}\n\n\tif h.OpId==\"writer\"&&tag==\"wrire\"{\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc ProxyTest(){\n\tvar devI Device\n\tdevI=&HardDiskProxy{OpId:\"admin\",hd:&HardDisk{}}\n\tdevI.Write([]byte(\"Hello world!\"))\n\tdata,_:=devI.Read()\n\tfmt.Println(string(data))\n\n\tdevI=&HardDiskProxy{OpId:\"reader\",hd:&HardDisk{storage:[]byte(\"only read\")}}\n\terr:=devI.Write([]byte(\"Hello world!\"))\n\tfmt.Println(err.Error())\n\tdata,_=devI.Read()\n\tfmt.Println(string(data))\n\n\tdevI=&HardDiskProxy{OpId:\"writer\",hd:&HardDisk{}}\n\terr=devI.Write([]byte(\"only writer\"))\n\tfmt.Println(err)\n\tdata,err=devI.Read()\n\tfmt.Println(string(data),err.Error())\n}"
  },
  {
    "path": "pattern/README.md",
    "content": "# 设计模式\n  * 创建型 C\n  * 结构型 J\n  * 行为型 X\n\n```\n   -AbstractFactory.go : 抽象工厂模式(C)\n   -Adapter.go : 适配器模式(J)\n   -Bridge.go : 桥接模式(J)\n   -Builder.go : 建造者模式(C)\n   -ChainOfResponsibility.go : 责任链模式(X)\n   -Command.go : 命令模式(X)\n   -Composite.go : 组合模式(J)\n   -Decorator.go : 装饰器模式(J)\n   -Facade.go : 外观模式(J)\n   -Factory.go : 工厂模式(C)\n   -Flyweight.go : 享元模式(J)\n   -Interpreter.go : 解释器模式(X)\n   -Iterator.go : 迭代器模式(X)\n   -Mediator.go : 中介者模式(X)\n   -Memento.go : 备忘录模式(X)\n   -Observer.go : 观察者模式(X)\n   -Prototype.go : 原型模式(C)\n   -Proxy.go : 代理模式(J)\n   -Singleton.go : 单例模式(C)\n   -Singleton2.go : 单例模式(C)\n   -State.go : 状态模式(X)\n   -Strategy.go : 策略模式(X)\n   -Template.go : 模板模式(X)\n   -Visitor.go : 访问者模式(X)\n```\n   \n# 参考资料\n* http://www.runoob.com/design-pattern/design-pattern-tutorial.html\n* http://www.cnblogs.com/beijiguangyong/archive/2010/11/15/2302807.html#_Toc281750448\n* http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html"
  },
  {
    "path": "pattern/Singleton.go",
    "content": "package pattern\n\nimport \"fmt\"\n\ntype Singleton interface {\n\tSaySomething()\n}\n\ntype singleton struct {\n}\n\nfunc (singleton) SaySomething() {\n\tfmt.Println(\"Singleton\")\n}\n\nvar singletonInstance Singleton\n\nfunc NewSingletonInstance() Singleton {\n\tif nil == singletonInstance {\n\t\tsingletonInstance = &singleton{}\n\t}\n\treturn singletonInstance\n}\n"
  },
  {
    "path": "pattern/Singleton2.go",
    "content": "package pattern\n\n//\n//另一种单例模式的实现方式，也是golang语言常用的模式\n//采用init（）方法全局之实例化一次\n//\n\nimport \"fmt\"\n\ntype Singleton2 interface {\n\tSaySomething()\n}\n\ntype singleton2 struct {\n}\n\nfunc (singleton2) SaySomething() {\n\tfmt.Println(\"Singleton\")\n}\n\nvar singletonInstance2 Singleton2\n\nfunc init() {\n\tsingletonInstance2 = new(singleton2)\n}\n\nfunc Singleton2SaySomething() {\n\tsingletonInstance2.SaySomething()\n}\n"
  },
  {
    "path": "pattern/State.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n// 状态模式（State Pattern）\n//   核心思想就是：当对象的状态改变时，同时改变其行为，很好理解！\n// 就拿QQ来说，有几种状态，在线、隐身、忙碌等，每个状态对应不同的操作，\n// 而且你的好友也能看到你的状态， 所以，状态模式就两点：\n//   1、可以通过改变状态来获得不同的行为。\n//   2、你的好友能同时看到你的变化\n\n\n// 相关模式：命令模式\n\n// 灯\ntype Light struct {\n     State LightState\n}\n\nfunc(l *Light)PressSwitch(){\n\tif l.State!=nil {\n\t\tl.State.PressSwitch(l)\n\t}\n}\n\n// 灯状态\ntype LightState  interface {\n\tPressSwitch(light *Light)\n}\n\n\ntype OnLightState struct {\n\n}\n\n// 开灯\nfunc(ols *OnLightState)PressSwitch(light *Light){\n\tfmt.Println(\"turn on light\")\n\t// 下一个状态动作为关灯\n\tlight.State=&OffLightState{}\n}\n\ntype OffLightState struct {\n\n}\n\n// 关灯\nfunc(ols *OffLightState)PressSwitch(light *Light){\n\tfmt.Println(\"turn off light\")\n\t// 下一个状态动作为开灯\n\tlight.State=&OnLightState{}\n}\n\nfunc StateTest(){\n\tlight:=&Light{State:&OnLightState{}}\n\tlight.PressSwitch()\n\tlight.PressSwitch()\n\tlight.PressSwitch()\n\tlight.PressSwitch()\n}"
  },
  {
    "path": "pattern/Strategy.go",
    "content": "package pattern\n\nimport (\n\t\"fmt\"\n)\n\n// 策略模式（Strategy Pattern）\n// 定义一系列的算法,把它们一个个封装起来,\n// 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。\n\n// 相关模式：工厂模式\n\ntype Strategy interface {\n\tDo(interface{})\n}\n\n// 从A到B\ntype AToB struct {\n\t// 距离\n\tABDistance float64\n        // 到达方式策略\n\tStrategy Strategy\n}\n\nfunc(ab *AToB) Do(){\n\tif ab.Strategy!=nil {\n\t\tab.Strategy.Do(ab)\n\t}\n}\n\ntype BikeStrategy struct {\n\tSpeed float64\n}\n\nfunc(bs *BikeStrategy) Do(ab interface{}){\n\taTob,ok:=ab.(*AToB)\n\tif ok &&bs.Speed<=0.0000001{\n\t\treturn\n\t}\n\tfmt.Println(\"方式：自行车 用时：\",aTob.ABDistance/bs.Speed)\n}\n\ntype BusStrategy struct {\n\tSpeed float64\n}\n\nfunc(bs *BusStrategy) Do(ab interface{}){\n\taTob,ok:=ab.(*AToB)\n\tif ok &&bs.Speed<=0.0000001{\n\t\treturn\n\t}\n\tfmt.Println(\"方式：巴士 用时：\",aTob.ABDistance/bs.Speed)\n}\n\ntype AirStrategy struct {\n\tSpeed float64\n}\n\nfunc(as *AirStrategy) Do(ab interface{}){\n\taTob,ok:=ab.(*AToB)\n\tif ok &&as.Speed<=0.0000001{\n\t\treturn\n\t}\n\tfmt.Println(\"方式：飞机 用时：\",aTob.ABDistance/as.Speed)\n}\n\nfunc StrategyTest(){\n        aTob:=&AToB{ABDistance:600}\n\n\taTob.Strategy=&BikeStrategy{Speed:15}\n\taTob.Do()\n\n\taTob.Strategy=&BusStrategy{Speed:90}\n\taTob.Do()\n\n\taTob.Strategy=&AirStrategy{Speed:500}\n\taTob.Do()\n\n}"
  },
  {
    "path": "pattern/Template.go",
    "content": "package pattern\n\nimport \"fmt\"\n\n// 模板模式（Template Pattern）\n//   定义一个操作中算法的框架，而将一些步骤延迟到子类中。\n// 模板方法模式使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。\n\ntype Game interface {\n\tStart()\n\tPlaying()\n\tEnd()\n}\n\ntype AbsGame struct {\n\n}\n\nfunc(ag *AbsGame)Start(){\n\tfmt.Println(\"start game\")\n}\nfunc(ag *AbsGame)Playing(){\n\tfmt.Println(\"game playing\")\n}\nfunc(ag *AbsGame)End(){\n\tfmt.Println(\"the end\")\n}\n\ntype FootBall struct {\n\t*AbsGame\n}\n\nfunc(fb *FootBall)Playing(){\n\tfmt.Println(\"playing FootBall\")\n}\n\ntype Cricket  struct {\n\t*AbsGame\n}\n\nfunc(fb *Cricket )Playing(){\n\tfmt.Println(\"playing Cricket \")\n}\n\nfunc RunGame(g Game){\n\tg.Start()\n\tg.Playing()\n\tg.End()\n}\n\nfunc TemplateTest(){\n\tRunGame(&FootBall{})\n\tRunGame(&Cricket{})\n}"
  },
  {
    "path": "pattern/Visitor.go",
    "content": "package pattern\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// 访问者模式（Visitor Pattern） 主要将数据结构与数据操作分离\n//\n// 1、对象结构中对象对应的类很少改变，但经常需要在此对象结构上定义新的操作。\n// 2、需要对一个对象结构中的对象进行很多不同的并且不相关的操作，而需要避免让这些操作\"污染\"这些对象的类，也不希望在增加新操作时修改这些类。\n\n\ntype Visitor interface {\n\tVisit(DataStruct)\n}\n\ntype DataStruct interface {\n\tAccept(Visitor)\n}\n\n\ntype ABData struct {\n\tA int\n\tB int\n}\nfunc (as *ABData)Accept(vi Visitor){\n\tvi.Visit(as)\n}\n\ntype AddVisitor struct {\n\n}\n\nfunc (av *AddVisitor)Visit(dataS DataStruct){\n\tdata:=dataS.(*ABData)\n\tsum:=data.A+data.B\n\tfmt.Println(\"A+B=\",sum)\n}\n\ntype SubVisitor struct {\n\n}\n\nfunc (sv *SubVisitor)Visit(dataS DataStruct){\n\tdata:=dataS.(*ABData)\n\tsum:=data.A-data.B\n\tfmt.Println(\"abs(A-B)=\",math.Abs(float64(sum)))\n}\n\nfunc VisitorTest(){\n\tData:=&ABData{A:8,B:10}\n\tadd:=&AddVisitor{}\n\tsub:=&SubVisitor{}\n\n\tData.Accept(add)\n\tData.Accept(sub)\n}"
  },
  {
    "path": "pattern/doc.go",
    "content": "//\n//  开发模式代码实现包\n// # 设计模式\n//  * 创建型 C\n//  * 结构型 J\n//  * 行为型 X\n//\n//   -AbstractFactory.go : 抽象工厂模式(C)\n//   -Adapter.go : 适配器模式(J)\n//   -Bridge.go : 桥接模式(J)\n//   -Builder.go : 建造者模式(C)\n//   -ChainOfResponsibility.go : 责任链模式(X)\n//   -Command.go : 命令模式(X)\n//   -Composite.go : 组合模式(J)\n//   -Decorator.go : 装饰器模式(J)\n//   -Facade.go : 外观模式(J)\n//   -Factory.go : 工厂模式(C)\n//   -Flyweight.go : 享元模式(J)\n//   -Interpreter.go : 解释器模式(X)\n//   -Iterator.go : 迭代器模式(X)\n//   -Mediator.go : 中介者模式(X)\n//   -Memento.go : 备忘录模式(X)\n//   -Observer.go : 观察者模式(X)\n//   -Prototype.go : 原型模式(C)\n//   -Proxy.go : 代理模式(J)\n//   -Singleton.go : 单例模式(C)\n//   -Singleton2.go : 单例模式(C)\n//   -State.go : 状态模式(X)\n//   -Strategy.go : 策略模式(X)\n//   -Template.go : 模板模式(X)\n//   -Visitor.go : 访问者模式(X)\n//\n//\npackage pattern\n"
  }
]