├── README.md ├── Proxy ├── Go │ ├── proxy │ │ ├── IDBQuery.go │ │ ├── DBQueryProxy.go │ │ └── DBQuery.go │ └── test.go ├── PHP │ ├── IDBQuery.php │ ├── test.php │ ├── DBQuery.php │ └── DBQueryProxy.php └── README.md ├── Decorator ├── PHP │ ├── CondimentDecorator.php │ ├── Beverage.php │ ├── Decaf.php │ ├── Espresso.php │ ├── DarkRoast.php │ ├── HouseBlend.php │ ├── Soy.php │ ├── Whip.php │ ├── Mocha.php │ └── test.php ├── Go │ ├── decorator │ │ ├── beverage.go │ │ ├── coffee.go │ │ ├── condiment.go │ │ ├── decaf.go │ │ ├── espresso.go │ │ ├── darkroast.go │ │ ├── houseblend.go │ │ ├── soy.go │ │ ├── whip.go │ │ └── mocha.go │ └── test.go └── README.md ├── Interpreter ├── PHP │ ├── Expression.php │ ├── SymbolExpression.php │ ├── ValueExpression.php │ ├── DivExpression.php │ ├── ModExpression.php │ ├── MulExpression.php │ ├── MinusExpression.php │ ├── PlusExpression.php │ ├── test.php │ └── Calculator.php ├── Go │ ├── interpreter │ │ ├── Expression.go │ │ ├── ValueExpression.go │ │ ├── SymbolExpression.go │ │ ├── DivExpression.go │ │ ├── ModExpression.go │ │ ├── MulExpression.go │ │ ├── PlusExpression.go │ │ ├── MinusExpression.go │ │ └── Calculator.go │ └── test.go └── README.md ├── Observer ├── Go │ ├── observer │ │ ├── observer.go │ │ ├── subject.go │ │ ├── observerA.go │ │ ├── observerB.go │ │ └── concreteSubject.go │ └── test.go ├── PHP │ ├── observer.php │ ├── subject.php │ ├── observerA.php │ ├── observerB.php │ ├── test.php │ └── concreteSubject.php └── README.md ├── ChainOfResponsibility ├── PHP │ ├── Filter.php │ ├── LengthFilter.php │ ├── HTMLFilter.php │ ├── MsgProcessor.php │ ├── test.php │ └── FilterChain.php ├── Go │ ├── chain │ │ ├── Filter.go │ │ ├── LengthFilter.go │ │ ├── HTMLFilter.go │ │ ├── MsgProcessor.go │ │ └── FilterChain.go │ └── test.go └── README.md ├── Visitor ├── Go │ ├── visitor │ │ ├── UserApi.go │ │ ├── UserVisitor.go │ │ ├── VipUser.go │ │ ├── NormalUser.go │ │ ├── ObjectStructure.go │ │ ├── User.go │ │ └── AddPointVisitor.go │ └── test.go ├── PHP │ ├── VipUser.php │ ├── UserVisitor.php │ ├── NormalUser.php │ ├── ObjectStructure.php │ ├── AddPointVisitor.php │ ├── User.php │ └── test.php └── README.md ├── Factory ├── AbstractFactory │ ├── PHP │ │ ├── PhoneFactory.php │ │ ├── IPhoneOS.php │ │ ├── AndroidOS.php │ │ ├── AndroidSpecial.php │ │ ├── IPhoneSpecial.php │ │ ├── IngredientFactory.php │ │ ├── OS.php │ │ ├── Special.php │ │ ├── OSFactory.php │ │ ├── SpecialFactory.php │ │ ├── AndroidFactory.php │ │ ├── IPhoneFactory.php │ │ ├── AndroidIgdFactory.php │ │ └── test.php │ ├── Go │ │ ├── abstractfactory │ │ │ ├── AndroidOS.go │ │ │ ├── IPhoneOS.go │ │ │ ├── OSI.go │ │ │ ├── SpecialI.go │ │ │ ├── AndroidSpecial.go │ │ │ ├── IPhoneSpecial.go │ │ │ ├── PhoneFactory.go │ │ │ ├── IngredientFactory.go │ │ │ ├── OS.go │ │ │ ├── Special.go │ │ │ ├── OSFactory.go │ │ │ ├── SpecialFactory.go │ │ │ ├── IPhoneFactory.go │ │ │ └── AndroidFactory.go │ │ └── test.go │ └── README.md └── FactoryMethod │ ├── PHP │ ├── PhoneFactory.php │ ├── Other.php │ ├── Android.php │ ├── IPhone.php │ ├── IPhoneFactory.php │ ├── OtherFactory.php │ ├── AndroidFactory.php │ ├── Phone.php │ └── test.php │ ├── Go │ ├── factorymethod │ │ ├── phoneProduct.go │ │ ├── PhoneFactory.go │ │ ├── Other.go │ │ ├── IPhone.go │ │ ├── Android.go │ │ ├── Phone.go │ │ ├── OtherFactory.go │ │ ├── AndroidFactory.go │ │ └── IPhoneFactory.go │ └── test.go │ └── README.md ├── Mediator ├── Go │ ├── mediator │ │ ├── ColleagueI.go │ │ ├── Mediator.go │ │ ├── Colleague.go │ │ ├── Controller.go │ │ ├── Model.go │ │ └── View.go │ └── test.go ├── PHP │ ├── Mediator.php │ ├── Colleague.php │ ├── View.php │ ├── test.php │ ├── Controller.php │ └── Model.php └── README.md ├── Bridge ├── PHP │ ├── MessageImplementor.php │ ├── MessageEmail.php │ ├── MessageMobile.php │ ├── MessageSMS.php │ ├── CommonMessage.php │ ├── AbstractMessage.php │ ├── UrgencyMessage.php │ ├── SpecialUrgencyMessage.php │ └── test.php ├── Go │ ├── bridge │ │ ├── MessageImplementor.go │ │ ├── MessageSMS.go │ │ ├── MessageEmail.go │ │ ├── MessageMobile.go │ │ ├── AbstractMessage.go │ │ ├── CommonMessage.go │ │ ├── UrgencyMessage.go │ │ └── SpecialUrgencyMessage.go │ └── test.go └── RAEDME.md ├── Command ├── Go │ ├── command │ │ ├── Command.go │ │ ├── Invoker.go │ │ ├── Player.go │ │ ├── PlayCommand.go │ │ ├── StopCommand.go │ │ └── PauseCommand.go │ └── test.go ├── PHP │ ├── Command.php │ ├── Invoker.php │ ├── Player.php │ ├── test.php │ ├── StopCommand.php │ ├── PauseCommand.php │ └── PlayCommand.php └── README.md ├── Flyweight ├── PHP │ ├── Flyweight.php │ ├── test.php │ ├── FlyweightFactory.php │ ├── AuthorizationFlyweight.php │ └── SecurityMgr.php ├── Go │ ├── flyweight │ │ ├── Flyweight.go │ │ ├── FlyweightFactory.go │ │ ├── AuthorizationFactory.go │ │ └── SecurityMgr.go │ └── test.go └── README.md ├── Strategy ├── Go │ ├── travel │ │ ├── travelStrategy.go │ │ ├── trainStrategy.go │ │ ├── bicycleStrategy.go │ │ ├── airplaneStrategy.go │ │ └── person.go │ └── test.go ├── PHP │ ├── travelStrategy.php │ ├── trainStrategy.php │ ├── airplaneStrategy.php │ ├── bicycleStrategy.php │ ├── person.php │ └── test.php └── README.md ├── Adapter ├── Go │ ├── adapter │ │ ├── LogDbOperateAPI.go │ │ ├── LogFileOperateAPI.go │ │ ├── logger.go │ │ ├── LogFileOperate.go │ │ └── LogAdapter.go │ └── test.go ├── PHP │ ├── LogDbOperateAPI.php │ ├── LogFileOperateAPI.php │ ├── test.php │ ├── LogFileOperate.php │ ├── Logger.php │ └── LogAdapter.php └── README.md ├── State ├── PHP │ ├── VoteState.php │ ├── BlackVoteState.php │ ├── RepeatVoteState.php │ ├── NormalVoteState.php │ ├── test.php │ ├── SpiteVoteState.php │ └── VoteManager.php ├── Go │ ├── state │ │ ├── VoteState.go │ │ ├── BlackVoteState.go │ │ ├── RepeatVoteState.go │ │ ├── NormalVoteState.go │ │ ├── SpiteVoteState.go │ │ └── VoteManager.go │ └── test.go └── README.md ├── TemplateMethod ├── Go │ ├── templatemethod │ │ ├── ViewEngine.go │ │ ├── HtmlView.go │ │ ├── BaseView.go │ │ └── JsonView.go │ └── test.go ├── PHP │ ├── HtmlView.php │ ├── JsonView.php │ ├── test.php │ └── ViewEngine.php └── README.md ├── Builder ├── Go │ ├── builder │ │ ├── builder.go │ │ ├── Director.go │ │ ├── TextBuilder.go │ │ └── XmlBuilder.go │ └── test.go ├── PHP │ ├── Builder.php │ ├── Director.php │ ├── TextBuilder.php │ ├── XmlBuilder.php │ └── test.php └── README.md ├── Facade ├── PHP │ ├── StoreDao.php │ ├── GoodsDao.php │ ├── test.php │ └── ServiceFacade.php ├── Go │ ├── facade │ │ ├── StoreDao.go │ │ ├── GoodsDao.go │ │ └── ServiceFacade.go │ └── test.go └── README.md ├── Singleton ├── PHP │ ├── test.php │ └── Singleton.php ├── GO │ ├── singleton │ │ └── singleton.go │ └── test.go └── README.md ├── Prototype ├── Go │ ├── prototype │ │ ├── ArticleApi.go │ │ ├── Author.go │ │ ├── TechArticle.go │ │ └── LifeArticle.go │ └── test.go ├── PHP │ ├── Author.php │ ├── Article.php │ ├── LifeArticle.php │ └── test.php └── README.md ├── Composite ├── Go │ ├── composite │ │ ├── ChildNavigation.go │ │ ├── NavigationComponent.go │ │ ├── BaseNavigation.go │ │ └── ParentNavigation.go │ └── test.go ├── PHP │ ├── ChildNavigation.php │ ├── NavigationComponent.php │ ├── test.php │ └── ParentNavigation.php └── README.md ├── Iterator ├── PHP │ ├── Goods.php │ ├── test.php │ ├── GoodsIterator.php │ └── GoodsList.php ├── Go │ ├── iterator │ │ ├── Goods.go │ │ ├── GoodsIterator.go │ │ └── GoodsList.go │ └── test.go └── README.md └── Memento ├── PHP ├── CareTaker.php ├── test.php ├── Memento.php └── Workout.php ├── Go ├── memento │ ├── CareTaker.go │ ├── Memento.go │ └── Workout.go └── test.go └── README.md /README.md: -------------------------------------------------------------------------------- 1 | # DesignPattern 2 | Implement Design Pattern using PHP and Go 3 | -------------------------------------------------------------------------------- /Proxy/Go/proxy/IDBQuery.go: -------------------------------------------------------------------------------- 1 | package proxy 2 | 3 | type IDBQuery interface { 4 | Request() 5 | } 6 | -------------------------------------------------------------------------------- /Proxy/PHP/IDBQuery.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /ChainOfResponsibility/PHP/Filter.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /Mediator/Go/mediator/ColleagueI.go: -------------------------------------------------------------------------------- 1 | package mediator 2 | 3 | type ColleagueI interface { 4 | GetMediator() Mediator 5 | } 6 | -------------------------------------------------------------------------------- /Bridge/PHP/MessageImplementor.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /Flyweight/PHP/Flyweight.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /Adapter/Go/adapter/LogDbOperateAPI.go: -------------------------------------------------------------------------------- 1 | package adapter 2 | 3 | type LogDbOperateAPI interface { 4 | CreateLog(logger Logger) 5 | } 6 | -------------------------------------------------------------------------------- /Adapter/PHP/LogDbOperateAPI.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /ChainOfResponsibility/Go/chain/Filter.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | type Filter interface { 4 | HandleFilter(str string) string 5 | } 6 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/Go/abstractfactory/SpecialI.go: -------------------------------------------------------------------------------- 1 | package abstractfactory 2 | 3 | type SpecialI interface { 4 | PhoneFactory 5 | } 6 | -------------------------------------------------------------------------------- /Observer/Go/observer/subject.go: -------------------------------------------------------------------------------- 1 | package observer 2 | 3 | type Subject interface { 4 | RegisterObserver(ob Observer) 5 | Notify() 6 | } 7 | -------------------------------------------------------------------------------- /State/PHP/VoteState.php: -------------------------------------------------------------------------------- 1 | name = "Other"; 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /Visitor/PHP/VipUser.php: -------------------------------------------------------------------------------- 1 | addPointForVip($this); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Adapter/PHP/LogFileOperateAPI.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/PHP/Android.php: -------------------------------------------------------------------------------- 1 | name = "Android"; 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/PHP/IPhone.php: -------------------------------------------------------------------------------- 1 | name = "IPhone"; 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /TemplateMethod/PHP/JsonView.php: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /Visitor/Go/visitor/UserVisitor.go: -------------------------------------------------------------------------------- 1 | package visitor 2 | 3 | type UserVisitor interface { 4 | AddPointForVip(vip_user *VipUser) 5 | AddPointForNormal(normal_user *NormalUser) 6 | } 7 | -------------------------------------------------------------------------------- /Visitor/PHP/NormalUser.php: -------------------------------------------------------------------------------- 1 | addPointForNormal($this); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /ChainOfResponsibility/PHP/LengthFilter.php: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/PHP/OtherFactory.php: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /Strategy/Go/travel/trainStrategy.go: -------------------------------------------------------------------------------- 1 | package travel 2 | 3 | type TrainStrategy struct { 4 | } 5 | 6 | func (ts TrainStrategy) traveler() string { 7 | return "Go to travel by train\n" 8 | } 9 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/IPhoneOS.php: -------------------------------------------------------------------------------- 1 | name operate system.\n"; 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /State/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./state" 4 | 5 | func main() { 6 | vm := state.NewVoteManager() 7 | for i := 0; i < 9; i++ { 8 | vm.Vote("tom", "A") 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Strategy/Go/travel/bicycleStrategy.go: -------------------------------------------------------------------------------- 1 | package travel 2 | 3 | type BicycleStrategy struct { 4 | } 5 | 6 | func (bs BicycleStrategy) traveler() string { 7 | return "Go to travel by bicycle\n" 8 | } 9 | -------------------------------------------------------------------------------- /ChainOfResponsibility/Go/chain/LengthFilter.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | type LengthFilter struct { 4 | } 5 | 6 | func (this *LengthFilter) HandleFilter(str string) string { 7 | return str[0:20] 8 | } 9 | -------------------------------------------------------------------------------- /Facade/PHP/GoodsDao.php: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/Go/abstractfactory/IngredientFactory.go: -------------------------------------------------------------------------------- 1 | package abstractfactory 2 | 3 | type IngredientFactory interface { 4 | createOS(name string) 5 | createSpecial(content string) 6 | } 7 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/AndroidOS.php: -------------------------------------------------------------------------------- 1 | name operate system.\n"; 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/AndroidSpecial.php: -------------------------------------------------------------------------------- 1 | content.\n"; 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/IPhoneSpecial.php: -------------------------------------------------------------------------------- 1 | content.\n"; 5 | } 6 | } 7 | ?> 8 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/PHP/AndroidFactory.php: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/PHP/Phone.php: -------------------------------------------------------------------------------- 1 | name; 7 | } 8 | } 9 | ?> 10 | -------------------------------------------------------------------------------- /Proxy/PHP/test.php: -------------------------------------------------------------------------------- 1 | request(); 8 | -------------------------------------------------------------------------------- /State/PHP/BlackVoteState.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /Mediator/Go/mediator/Mediator.go: -------------------------------------------------------------------------------- 1 | package mediator 2 | 3 | type Mediator interface { 4 | AddUser(user string) 5 | GetUserList() []string 6 | DeleteUser(user string) 7 | ShowResult(result string) 8 | } 9 | -------------------------------------------------------------------------------- /Bridge/PHP/MessageEmail.php: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /Singleton/PHP/test.php: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /Strategy/PHP/trainStrategy.php: -------------------------------------------------------------------------------- 1 | 10 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/OS.php: -------------------------------------------------------------------------------- 1 | name = $name; 7 | } 8 | } 9 | ?> 10 | -------------------------------------------------------------------------------- /Strategy/PHP/airplaneStrategy.php: -------------------------------------------------------------------------------- 1 | 10 | -------------------------------------------------------------------------------- /Strategy/PHP/bicycleStrategy.php: -------------------------------------------------------------------------------- 1 | 10 | -------------------------------------------------------------------------------- /Bridge/Go/bridge/MessageSMS.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | import "fmt" 4 | 5 | type MessageSMS struct { 6 | } 7 | 8 | func (this *MessageSMS) Send(msg string, user string) { 9 | fmt.Println("使用站内短消息发送" + msg + "给" + user) 10 | } 11 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/Go/abstractfactory/Special.go: -------------------------------------------------------------------------------- 1 | package abstractfactory 2 | 3 | type Special struct { 4 | Content string 5 | SpecialI 6 | } 7 | 8 | func (self *Special) Create() string { 9 | return self.Content 10 | } 11 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/Go/factorymethod/OtherFactory.go: -------------------------------------------------------------------------------- 1 | package factorymethod 2 | 3 | type OtherFactory struct { 4 | PhoneFactory 5 | } 6 | 7 | func (this *OtherFactory) CreatePhone() phoneProduct { 8 | return NewOther() 9 | } 10 | -------------------------------------------------------------------------------- /Prototype/Go/prototype/ArticleApi.go: -------------------------------------------------------------------------------- 1 | package prototype 2 | 3 | type ArticleApi interface { 4 | Clone() ArticleApi 5 | GetTitle() string 6 | SetTitle(name string) 7 | SetAuthor(author *Author) 8 | GetAuthor() *Author 9 | } 10 | -------------------------------------------------------------------------------- /Bridge/Go/bridge/MessageEmail.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | import "fmt" 4 | 5 | type MessageEmail struct { 6 | } 7 | 8 | func (this *MessageEmail) Send(msg string, user string) { 9 | fmt.Println("使用Email发送" + msg + "给" + user) 10 | } 11 | -------------------------------------------------------------------------------- /Bridge/Go/bridge/MessageMobile.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | import "fmt" 4 | 5 | type MessageMobile struct { 6 | } 7 | 8 | func (this *MessageMobile) Send(msg string, user string) { 9 | fmt.Println("使用手机发送" + msg + "给" + user) 10 | } 11 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/Go/factorymethod/AndroidFactory.go: -------------------------------------------------------------------------------- 1 | package factorymethod 2 | 3 | type AndroidFactory struct { 4 | PhoneFactory 5 | } 6 | 7 | func (this *AndroidFactory) CreatePhone() phoneProduct { 8 | return NewAndroid() 9 | } 10 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/Go/factorymethod/IPhoneFactory.go: -------------------------------------------------------------------------------- 1 | package factorymethod 2 | 3 | type IPhoneFactory struct { 4 | PhoneFactory 5 | } 6 | 7 | func (this *IPhoneFactory) CreatePhone() phoneProduct { 8 | return NewIPhone() 9 | } 10 | -------------------------------------------------------------------------------- /State/PHP/NormalVoteState.php: -------------------------------------------------------------------------------- 1 | add($user, $vote_item); 5 | echo "投票成功\n"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Bridge/Go/bridge/AbstractMessage.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | type AbstractMessage struct { 4 | Impl MessageImplementor 5 | } 6 | 7 | func (this *AbstractMessage) SendMessage(msg string, user string) { 8 | this.Impl.Send(msg, user) 9 | } 10 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/Special.php: -------------------------------------------------------------------------------- 1 | content = $content; 7 | } 8 | } 9 | ?> 10 | -------------------------------------------------------------------------------- /Bridge/Go/bridge/CommonMessage.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | type CommonMessage struct { 4 | *AbstractMessage 5 | } 6 | 7 | func (this *CommonMessage) SendMessage(msg string, user string) { 8 | this.AbstractMessage.SendMessage(msg, user) 9 | } 10 | -------------------------------------------------------------------------------- /Mediator/PHP/Mediator.php: -------------------------------------------------------------------------------- 1 | name = $name; 7 | } 8 | 9 | public function getName() { 10 | return $this->name; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ChainOfResponsibility/PHP/HTMLFilter.php: -------------------------------------------------------------------------------- 1 | ", ">", $str); 6 | return $str; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Iterator/Go/iterator/Goods.go: -------------------------------------------------------------------------------- 1 | package iterator 2 | 3 | type Goods struct { 4 | Name string 5 | } 6 | 7 | func NewGoods(name string) *Goods { 8 | return &Goods{Name: name} 9 | } 10 | 11 | func (this *Goods) GetName() string { 12 | return this.Name 13 | } 14 | -------------------------------------------------------------------------------- /Proxy/Go/proxy/DBQueryProxy.go: -------------------------------------------------------------------------------- 1 | package proxy 2 | 3 | type DBQueryProxy struct { 4 | real *DBQuery 5 | } 6 | 7 | func (this *DBQueryProxy) Request() { 8 | if this.real == nil { 9 | this.real = NewDBQuery() 10 | } 11 | 12 | this.real.Request() 13 | } 14 | -------------------------------------------------------------------------------- /State/Go/state/BlackVoteState.go: -------------------------------------------------------------------------------- 1 | package state 2 | 3 | import "fmt" 4 | 5 | type BlackVoteState struct { 6 | votestate 7 | } 8 | 9 | func (this *BlackVoteState) HandleVote(user_name string, item string, vm *VoteManager) { 10 | fmt.Printf("你已进入黑名单") 11 | } 12 | -------------------------------------------------------------------------------- /TemplateMethod/Go/templatemethod/HtmlView.go: -------------------------------------------------------------------------------- 1 | package templatemethod 2 | 3 | type HtmlView struct { 4 | viewengine 5 | *BaseView 6 | } 7 | 8 | func (hv *HtmlView) PackData(data [2]string) string { 9 | return "code: " + data[0] + " result: " + data[1] 10 | } 11 | -------------------------------------------------------------------------------- /State/Go/state/RepeatVoteState.go: -------------------------------------------------------------------------------- 1 | package state 2 | 3 | import "fmt" 4 | 5 | type RepeatVoteState struct { 6 | votestate 7 | } 8 | 9 | func (this *RepeatVoteState) HandleVote(user_name string, item string, vm *VoteManager) { 10 | fmt.Printf("请不要重复投票\n") 11 | } 12 | -------------------------------------------------------------------------------- /TemplateMethod/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./templatemethod" 4 | 5 | func main() { 6 | json_view := &templatemethod.JsonView{} 7 | json_view.Render(json_view) 8 | 9 | html_view := &templatemethod.HtmlView{} 10 | html_view.Render(html_view) 11 | } 12 | -------------------------------------------------------------------------------- /Bridge/Go/bridge/UrgencyMessage.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | type UrgencyMessage struct { 4 | *AbstractMessage 5 | } 6 | 7 | func (this *UrgencyMessage) SendMessage(msg string, user string) { 8 | msg = "紧急" + msg 9 | this.AbstractMessage.SendMessage(msg, user) 10 | } 11 | -------------------------------------------------------------------------------- /Singleton/GO/singleton/singleton.go: -------------------------------------------------------------------------------- 1 | package singleton 2 | 3 | type Singleton struct { 4 | } 5 | 6 | var instance *Singleton 7 | 8 | func GetInstance() *Singleton { 9 | if instance == nil { 10 | instance = &Singleton{} 11 | } 12 | 13 | return instance 14 | } 15 | -------------------------------------------------------------------------------- /Memento/PHP/CareTaker.php: -------------------------------------------------------------------------------- 1 | memento = $memento; 7 | } 8 | 9 | public function retriveMemento() { 10 | return $this->memento; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /TemplateMethod/PHP/test.php: -------------------------------------------------------------------------------- 1 | render(); 8 | 9 | $html_view = new HtmlView(); 10 | $html_view->render(); 11 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/OSFactory.php: -------------------------------------------------------------------------------- 1 | name = $name; 7 | } 8 | 9 | public function getName() { 10 | return $this->name; 11 | } 12 | } 13 | ?> 14 | -------------------------------------------------------------------------------- /Singleton/GO/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "./singleton" 5 | 6 | func main() { 7 | instance := singleton.GetInstance() 8 | another_instance := singleton.GetInstance() 9 | if instance != another_instance { 10 | fmt.Printf("not equal"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Bridge/Go/bridge/SpecialUrgencyMessage.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | type SpecialUrgencyMessage struct { 4 | *AbstractMessage 5 | } 6 | 7 | func (this *SpecialUrgencyMessage) SendMessage(msg string, user string) { 8 | msg = "加急" + msg 9 | this.AbstractMessage.SendMessage(msg, user) 10 | } 11 | -------------------------------------------------------------------------------- /Visitor/Go/visitor/VipUser.go: -------------------------------------------------------------------------------- 1 | package visitor 2 | 3 | type VipUser struct { 4 | *User 5 | } 6 | 7 | func NewVipUser(name string) *VipUser { 8 | return &VipUser{&User{name, 0}} 9 | } 10 | 11 | func (this *VipUser) Accept(visitor UserVisitor) { 12 | visitor.AddPointForVip(this) 13 | } 14 | -------------------------------------------------------------------------------- /Bridge/PHP/CommonMessage.php: -------------------------------------------------------------------------------- 1 | description = "Coffee"; 7 | } 8 | 9 | public abstract function cost(); 10 | public abstract function getDescription(); 11 | } 12 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/SpecialFactory.php: -------------------------------------------------------------------------------- 1 | name = $name; 7 | } 8 | 9 | public function getName() { 10 | return $this->name; 11 | } 12 | } 13 | ?> 14 | -------------------------------------------------------------------------------- /Interpreter/PHP/SymbolExpression.php: -------------------------------------------------------------------------------- 1 | left = $left; 8 | $this->right = $right; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Mediator/PHP/Colleague.php: -------------------------------------------------------------------------------- 1 | mediator = $mediator; 7 | } 8 | 9 | protected function getMeditor() { 10 | return $this->mediator; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /State/Go/state/NormalVoteState.go: -------------------------------------------------------------------------------- 1 | package state 2 | 3 | import "fmt" 4 | 5 | type NormalVoteState struct { 6 | votestate 7 | } 8 | 9 | func (this *NormalVoteState) HandleVote(user_name string, item string, vm *VoteManager) { 10 | vm.Add(user_name, item) 11 | fmt.Printf("投票成功\n") 12 | } 13 | -------------------------------------------------------------------------------- /Composite/PHP/ChildNavigation.php: -------------------------------------------------------------------------------- 1 | name = $name; 7 | } 8 | 9 | public function getName() { 10 | return $this->name; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Memento/Go/memento/CareTaker.go: -------------------------------------------------------------------------------- 1 | package memento 2 | 3 | type CareTaker struct { 4 | memento *Memento 5 | } 6 | 7 | func (this *CareTaker) SaveMemento(memento *Memento) { 8 | this.memento = memento 9 | } 10 | 11 | func (this *CareTaker) RetriveMemento() *Memento { 12 | return this.memento 13 | } 14 | -------------------------------------------------------------------------------- /Interpreter/PHP/ValueExpression.php: -------------------------------------------------------------------------------- 1 | value = $value; 7 | } 8 | 9 | public function calculate() { 10 | return $this->value; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Mediator/Go/mediator/Colleague.go: -------------------------------------------------------------------------------- 1 | package mediator 2 | 3 | type Colleague struct { 4 | mediator Mediator 5 | } 6 | 7 | func NewColleague(mediator Mediator) *Colleague { 8 | return &Colleague{mediator} 9 | } 10 | 11 | func (this *Colleague) GetMediator() Mediator { 12 | return this.mediator 13 | } 14 | -------------------------------------------------------------------------------- /Proxy/Go/proxy/DBQuery.go: -------------------------------------------------------------------------------- 1 | package proxy 2 | 3 | import "fmt" 4 | 5 | type DBQuery struct { 6 | IDBQuery 7 | } 8 | 9 | func NewDBQuery() *DBQuery { 10 | fmt.Printf("Connecting...\n") 11 | return &DBQuery{} 12 | } 13 | 14 | func (this *DBQuery) Request() { 15 | fmt.Printf("Requesting...\n") 16 | } 17 | -------------------------------------------------------------------------------- /Proxy/PHP/DBQueryProxy.php: -------------------------------------------------------------------------------- 1 | real == null) { 7 | $this->real = new DBQuery(); 8 | } 9 | 10 | return $this->real->request(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Bridge/PHP/AbstractMessage.php: -------------------------------------------------------------------------------- 1 | impl = $impl; 7 | } 8 | 9 | public function sendMessage($msg, $user) { 10 | $this->impl->send($msg, $user); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Flyweight/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./flyweight" 4 | import "fmt" 5 | 6 | func main() { 7 | mgr := flyweight.GetSInstance() 8 | mgr.Login("hhq") 9 | mgr.Login("tom") 10 | fmt.Println(mgr.HasPermit("hhq", "money", "look")) 11 | fmt.Println(mgr.HasPermit("tom", "money", "look")) 12 | } 13 | -------------------------------------------------------------------------------- /Visitor/Go/visitor/NormalUser.go: -------------------------------------------------------------------------------- 1 | package visitor 2 | 3 | type NormalUser struct { 4 | *User 5 | } 6 | 7 | func NewNormalUser(name string) *NormalUser { 8 | return &NormalUser{&User{name, 0}} 9 | } 10 | 11 | func (this *NormalUser) Accept(visitor UserVisitor) { 12 | visitor.AddPointForNormal(this) 13 | } 14 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/coffee.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type Coffee struct { 4 | beverage 5 | price float64 6 | description string 7 | } 8 | 9 | func (self *Coffee) Cost() float64 { 10 | return self.price 11 | } 12 | 13 | func (self *Coffee) GetDescription() string { 14 | return self.description 15 | } 16 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/AndroidFactory.php: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/IPhoneFactory.php: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/ValueExpression.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | type ValueExpression struct { 4 | value int 5 | } 6 | 7 | func NewValueExpression(value int) *ValueExpression { 8 | return &ValueExpression{value} 9 | } 10 | 11 | func (this *ValueExpression) Calculate() int { 12 | return this.value 13 | } 14 | -------------------------------------------------------------------------------- /Adapter/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./adapter" 4 | 5 | func main() { 6 | lg := new(adapter.Logger) 7 | lg.SetLogId("111") 8 | lg.SetOpeUserId("user_tom"); 9 | logFileOperate_api := adapter.NewLogFileOperate(""); 10 | db_api := adapter.NewLogAdapter(logFileOperate_api) 11 | db_api.CreateLog(lg) 12 | } 13 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/SymbolExpression.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | type SymbolExpression struct { 4 | Expression 5 | Left Expression 6 | Right Expression 7 | } 8 | 9 | func NewSymbolExpression(Left Expression, Right Expression) *SymbolExpression { 10 | return &SymbolExpression{Left: Left, Right: Right} 11 | } 12 | -------------------------------------------------------------------------------- /Bridge/PHP/UrgencyMessage.php: -------------------------------------------------------------------------------- 1 | ", ">", -1) 11 | return result 12 | } 13 | -------------------------------------------------------------------------------- /Interpreter/PHP/DivExpression.php: -------------------------------------------------------------------------------- 1 | left->calculate() / $this->right->calculate(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Interpreter/PHP/ModExpression.php: -------------------------------------------------------------------------------- 1 | left->calculate() % $this->right->calculate(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Interpreter/PHP/MulExpression.php: -------------------------------------------------------------------------------- 1 | left->calculate() * $this->right->calculate(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Interpreter/PHP/MinusExpression.php: -------------------------------------------------------------------------------- 1 | left->calculate() - $this->left->calculate(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Interpreter/PHP/PlusExpression.php: -------------------------------------------------------------------------------- 1 | left->calculate() + $this->right->calculate(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Interpreter/README.md: -------------------------------------------------------------------------------- 1 | ## 解释器模式 2 | 3 | ### 概述 4 | 解释器模式是给定一种语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。一般一个解释器处理一条语法规则。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 使用数学运算来实现解释器模式。定义数学运算的步骤以及数学表达式的解析器。输入表达式后得出结果。 11 | 12 | ### 总结与分析 13 | 解释器的本质是分离实现,解释执行。解释器模式适合用在语法比较简单的语法解析。 14 | -------------------------------------------------------------------------------- /Observer/Go/observer/observerA.go: -------------------------------------------------------------------------------- 1 | package observer 2 | 3 | import "fmt" 4 | 5 | type ObserverA struct { 6 | value string 7 | } 8 | 9 | func (ob ObserverA) Update(val string) { 10 | ob.value = val 11 | ob.Display() 12 | } 13 | 14 | func (ob ObserverA) Display() { 15 | fmt.Printf("observer A value is " + ob.value + "\n") 16 | } 17 | -------------------------------------------------------------------------------- /Observer/Go/observer/observerB.go: -------------------------------------------------------------------------------- 1 | package observer 2 | 3 | import "fmt" 4 | 5 | type ObserverB struct { 6 | value string 7 | } 8 | 9 | func (ob ObserverB) Update(val string) { 10 | ob.value = val 11 | ob.Display() 12 | } 13 | 14 | func (ob ObserverB) Display() { 15 | fmt.Printf("observer B value is " + ob.value + "\n") 16 | } 17 | -------------------------------------------------------------------------------- /Observer/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./observer" 4 | 5 | func main() { 6 | subject := new(observer.ConcreteSubject) 7 | observerA := new(observer.ObserverA) 8 | observerB := new(observer.ObserverB) 9 | 10 | subject.RegisterObserver(observerA) 11 | subject.RegisterObserver(observerB) 12 | 13 | subject.SetValue("5") 14 | } 15 | -------------------------------------------------------------------------------- /Bridge/PHP/SpecialUrgencyMessage.php: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /Iterator/README.md: -------------------------------------------------------------------------------- 1 | ## 迭代器模式 2 | 3 | ### 概述 4 | 迭代器模式提供一种方法,使得可以顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 使用商品列表作为聚合对象,迭代器实现获得当前元素,移动到下一个元素,判断当前元素是否有效,获得当前元素的下标以及重置到第一个元素的接口。 11 | 12 | ### 总结与分析 13 | 迭代器模式将便利的任务放在迭代器上,而不是聚合对象上。这样既简化了聚合对象的接口和实现,也让责任各得其所。 14 | -------------------------------------------------------------------------------- /Prototype/PHP/Author.php: -------------------------------------------------------------------------------- 1 | name = $name; 7 | } 8 | 9 | public function setName($name) { 10 | $this->name = $name; 11 | } 12 | 13 | public function getName() { 14 | return $this->name; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Strategy/PHP/person.php: -------------------------------------------------------------------------------- 1 | _strategy = $strategy; 9 | } 10 | 11 | public function travel() 12 | { 13 | $this->_strategy->travelAlgorithm(); 14 | } 15 | } 16 | ?> 17 | -------------------------------------------------------------------------------- /Command/PHP/Invoker.php: -------------------------------------------------------------------------------- 1 | command = $cmd; 7 | } 8 | 9 | public function run() { 10 | $this->command->excute(); 11 | } 12 | 13 | public function undo() { 14 | $this->command->undo(); 15 | } 16 | } 17 | ?> 18 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/condiment.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type Condiment struct { 4 | *Coffee 5 | beverage beverage 6 | price float64 7 | description string 8 | } 9 | 10 | func (self *Condiment) Cost() float64 { 11 | return self.price 12 | } 13 | 14 | func (self *Condiment) GetDescription() string { 15 | return self.description 16 | } 17 | -------------------------------------------------------------------------------- /Prototype/PHP/Article.php: -------------------------------------------------------------------------------- 1 | title; 11 | } 12 | 13 | public function setTitle($title) { 14 | $this->title = $title; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Strategy/Go/travel/person.go: -------------------------------------------------------------------------------- 1 | package travel 2 | 3 | type Person struct { 4 | _strategy TravelStrategy 5 | } 6 | 7 | func SetStrategy(strategy TravelStrategy) Person { 8 | person := new(Person) 9 | 10 | person._strategy = strategy 11 | 12 | return *person 13 | } 14 | 15 | func (p Person) Travel() string { 16 | return p._strategy.traveler(); 17 | } 18 | -------------------------------------------------------------------------------- /Decorator/PHP/Decaf.php: -------------------------------------------------------------------------------- 1 | description = " Decaf"; 6 | } 7 | 8 | public function cost() { 9 | return 6.0; 10 | } 11 | 12 | public function getDescription() { 13 | return $this->description; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Interpreter/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "./interpreter" 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | statement := "3 * 2 * 4" 10 | calculator := &interpreter.Calculator{Symbol_arr: [5]string{"+", "-", "*", "/", "%"}} 11 | calculator.Init(statement) 12 | result := calculator.Compute() 13 | fmt.Printf("%s = %d\n", statement, result) 14 | } 15 | -------------------------------------------------------------------------------- /Observer/PHP/observerA.php: -------------------------------------------------------------------------------- 1 | _value = $value; 9 | $this->display(); 10 | } 11 | 12 | public function display() { 13 | echo "Observer A value is " . $this->_value . "\n"; 14 | } 15 | } 16 | ?> 17 | -------------------------------------------------------------------------------- /Observer/PHP/observerB.php: -------------------------------------------------------------------------------- 1 | _value = $value; 9 | $this->display(); 10 | } 11 | 12 | public function display() { 13 | echo "Observer B value is " . $this->_value . "\n"; 14 | } 15 | } 16 | ?> 17 | -------------------------------------------------------------------------------- /Singleton/PHP/Singleton.php: -------------------------------------------------------------------------------- 1 | 16 | -------------------------------------------------------------------------------- /State/Go/state/SpiteVoteState.go: -------------------------------------------------------------------------------- 1 | package state 2 | 3 | import "fmt" 4 | 5 | type SpiteVoteState struct { 6 | votestate 7 | } 8 | 9 | func (this *SpiteVoteState) HandleVote(user_name string, item string, vm *VoteManager) { 10 | if _, ok := vm.Votes[user_name];ok { 11 | delete(vm.Votes, user_name) 12 | } 13 | 14 | fmt.Printf("你有恶意刷票行为,取消投票资格\n") 15 | } 16 | -------------------------------------------------------------------------------- /Command/Go/command/Invoker.go: -------------------------------------------------------------------------------- 1 | package command 2 | 3 | type Invoker struct { 4 | command command 5 | } 6 | 7 | func (this *Invoker) SetCommand(cmd command) { 8 | this.command = cmd 9 | } 10 | 11 | func (this *Invoker) Run() string { 12 | return this.command.Excute() 13 | } 14 | 15 | func (this *Invoker) Undo() string { 16 | return this.command.Undo() 17 | } 18 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/decaf.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type Decaf struct { 4 | *Coffee 5 | } 6 | 7 | func NewDecaf() *Decaf { 8 | return &Decaf{&Coffee{price: 2.5, description: "Decaf"}} 9 | } 10 | 11 | func (self *Decaf) Cost() float64 { 12 | return self.price 13 | } 14 | 15 | func (self *Decaf) GetDescription() string { 16 | return self.description 17 | } 18 | -------------------------------------------------------------------------------- /Facade/PHP/test.php: -------------------------------------------------------------------------------- 1 | goodsDetail(); 11 | var_dump($goods_detail); 12 | -------------------------------------------------------------------------------- /Decorator/PHP/Espresso.php: -------------------------------------------------------------------------------- 1 | description = " Espresso"; 6 | } 7 | 8 | public function cost() { 9 | return 5.6; 10 | } 11 | 12 | public function getDescription() { 13 | return $this->description; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Composite/README.md: -------------------------------------------------------------------------------- 1 | ## 组合模式 2 | 3 | ### 概述 4 | 树形结构在项目中很经常会碰到,当树形结构变得越来越大之后会难以管理。组合模式允许你将对象组合成树形结构来表现“整体/部分”的层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。树里面包含了组合以及个别的对象。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 本例中,用组合模式来实现导航栏。可以有多级导航栏和二级导航栏。 11 | 12 | ### 总结与分析 13 | 使用组合模式,可以将相同的操作应用在组合和个别的对象上,换句话说,在大多数情况下,我们可以忽略对象组合和个别对象之间的差别。 14 | -------------------------------------------------------------------------------- /Decorator/PHP/DarkRoast.php: -------------------------------------------------------------------------------- 1 | description = " DarkRoast"; 6 | } 7 | 8 | public function cost() { 9 | return 5.0; 10 | } 11 | 12 | public function getDescription() { 13 | return $this->description; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Decorator/PHP/HouseBlend.php: -------------------------------------------------------------------------------- 1 | description = " HouseBlend"; 6 | } 7 | 8 | public function cost() { 9 | return 8.9; 10 | } 11 | 12 | public function getDescription() { 13 | return $this->description; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /ChainOfResponsibility/README.md: -------------------------------------------------------------------------------- 1 | ## 职责链模式 2 | 3 | ### 概述 4 | 职责链模式是使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 使用数据过滤类来实现职责链模式。用户传递数据给FilterChain类,但是数据具体会被哪个过滤器处理客户并不知道,FilterChain最终会返回被过滤后的数据给用户。 11 | 12 | ### 总结与分析 13 | 职责链模式让请求者和接收者解耦,从而可以动态地切换和组合接收者。 14 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/Go/abstractfactory/SpecialFactory.go: -------------------------------------------------------------------------------- 1 | package abstractfactory 2 | 3 | type SpecialFactory struct { 4 | Content string 5 | } 6 | 7 | func NewSpecialFactory(content string) *SpecialFactory { 8 | sf := new(SpecialFactory) 9 | sf.Content = content 10 | return sf 11 | } 12 | 13 | func (sf *SpecialFactory) GetContent() string { 14 | return sf.Content 15 | } 16 | -------------------------------------------------------------------------------- /Memento/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./memento" 4 | 5 | func main() { 6 | workout := memento.NewWorkout() 7 | workout.Running() 8 | care_taker := &memento.CareTaker{} 9 | memento := workout.CreateMemento() 10 | care_taker.SaveMemento(memento) 11 | 12 | workout.Bicycle() 13 | workout.SetMemento(care_taker.RetriveMemento()) 14 | workout.AbdominalRipperX() 15 | } 16 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/espresso.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type Espresso struct { 4 | *Coffee 5 | } 6 | 7 | func NewEspresso() *Espresso { 8 | return &Espresso{&Coffee{price: 1.0, description: "Espresso"}} 9 | } 10 | 11 | func (self *Espresso) Cost() float64 { 12 | return self.price 13 | } 14 | 15 | func (self Espresso) GetDescription() string { 16 | return self.description 17 | } 18 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/darkroast.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type DarkRoast struct { 4 | *Coffee 5 | } 6 | 7 | func NewDarkRoast() *DarkRoast { 8 | return &DarkRoast{&Coffee{price: 2.0, description: "DarkRoast"}} 9 | } 10 | 11 | func (self *DarkRoast) Cost() float64 { 12 | return self.price 13 | } 14 | 15 | func (self *DarkRoast) GetDescription() string { 16 | return self.description 17 | } 18 | -------------------------------------------------------------------------------- /Facade/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "./facade" 5 | 6 | func main() { 7 | store_dao := &facade.StoreDao{} 8 | goods_dao := &facade.GoodsDao{} 9 | 10 | goods_service := &facade.ServiceFacade{store_dao, goods_dao} 11 | goods_detail := goods_service.GoodsDetail() 12 | 13 | for i := range goods_detail { 14 | fmt.Printf("%s\n", goods_detail[i]) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /State/PHP/test.php: -------------------------------------------------------------------------------- 1 | vote("u1","A"); 12 | } 13 | -------------------------------------------------------------------------------- /TemplateMethod/Go/templatemethod/BaseView.go: -------------------------------------------------------------------------------- 1 | package templatemethod 2 | 3 | import "fmt" 4 | 5 | type BaseView struct { 6 | } 7 | 8 | func (bv *BaseView) GetData() [2]string { 9 | return [2]string{"200", "success"} 10 | } 11 | 12 | func (self *BaseView) Render(viewengine viewengine) { 13 | data := self.GetData() 14 | result := viewengine.PackData(data) 15 | fmt.Printf(result + "\n") 16 | } 17 | -------------------------------------------------------------------------------- /Builder/PHP/Director.php: -------------------------------------------------------------------------------- 1 | builder = $builder; 7 | } 8 | 9 | public function construct($header, $body, $footer) { 10 | $this->builder->buildHeader($header); 11 | $this->builder->buildBody($body); 12 | $this->builder->buildFooter($footer); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ChainOfResponsibility/Go/chain/MsgProcessor.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | type MsgProcessor struct { 4 | msg string 5 | filter_chain *FilterChain 6 | } 7 | 8 | func NewMsgProcessor(msg string, filter_chain *FilterChain) *MsgProcessor { 9 | return &MsgProcessor{msg, filter_chain} 10 | } 11 | 12 | func (this *MsgProcessor) Process() string { 13 | return this.filter_chain.HandleFilter(this.msg) 14 | } 15 | -------------------------------------------------------------------------------- /ChainOfResponsibility/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./chain" 4 | import "fmt" 5 | 6 | func main() { 7 | msg := "
hello, i am tom.how are you?
" 8 | filter_chain := chain.NewFilterChain() 9 | filter_chain.AddFilter(&chain.HTMLFilter{}).AddFilter(&chain.LengthFilter{}) 10 | msg_processor := chain.NewMsgProcessor(msg, filter_chain) 11 | fmt.Println(msg_processor.Process()) 12 | } 13 | -------------------------------------------------------------------------------- /ChainOfResponsibility/PHP/MsgProcessor.php: -------------------------------------------------------------------------------- 1 | msg = $msg; 8 | $this->filter_chain = $filter_chain; 9 | } 10 | 11 | public function process() { 12 | return $this->filter_chain->handleFilter($this->msg); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TemplateMethod/PHP/ViewEngine.php: -------------------------------------------------------------------------------- 1 | 200, 'data' => array('name' => 'tom', 'age' => 22)); 7 | } 8 | 9 | public final function render() { 10 | $data = $this->getData(); 11 | var_dump($this->packData($data)); 12 | } 13 | } 14 | ?> 15 | -------------------------------------------------------------------------------- /Adapter/README.md: -------------------------------------------------------------------------------- 1 | ## 适配器模式 2 | 3 | ### 概述 4 | 在开发过程会遇到有两个项目,A项目想调用B项目的接口,然而两个项目并没有做兼容。适配器模式就将一个类的接口,转换成客户期望的另一个接口。适配器模式就好比IPhone手机的转换器一样。还有Javachoking的swing库也有很多Adapter也是适配器模式应用的场景。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 实现使用适配Log类。当Log实现了保存到文件的功能后,客户想实现保存到数据库,使用适配器模式可以实现。 11 | 12 | ### 总结与分析 13 | 适配器模式的主要目的是组合两个不相干的类,在不改变原有系统的基础上,提供新的接口服务。 14 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/houseblend.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type HouseBlend struct { 4 | *Coffee 5 | } 6 | 7 | func NewHouseBlend() *HouseBlend { 8 | return &HouseBlend{&Coffee{price: 3.0, description: "HouseBlend"}} 9 | } 10 | 11 | func (self *HouseBlend) Cost() float64 { 12 | return self.price 13 | } 14 | 15 | func (self *HouseBlend) GetDescription() string { 16 | return self.description 17 | } 18 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/README.md: -------------------------------------------------------------------------------- 1 | ## 抽象工厂模式 2 | 3 | ### 概述 4 | 抽象工厂提供一个接口,用于创建相关或依赖对象的家族,而不需要明确制定具体类。它允许可与使用抽象的接口来创建一组相关的产品,而不需要知道实际产出的具体产品是什么。这样一来,客户就从具体的产品种被解耦。抽象工厂模式也遵循了依赖倒置原则,指导我们避免依赖具体类型,而要具体依赖抽象。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 本例使用手机的操作系统和特殊应用作为抽象工厂类。不同的手机作为具体产品。 11 | 12 | ### 总结与分析 13 | 抽象工厂帮助我们将具体实现作封装抽象起来,一边的到更松耦合,更有弹性的设计。 14 | -------------------------------------------------------------------------------- /Visitor/Go/visitor/ObjectStructure.go: -------------------------------------------------------------------------------- 1 | package visitor 2 | 3 | type ObjectStructure struct { 4 | user_list []UserApi 5 | } 6 | 7 | func (this *ObjectStructure) AddUser(user UserApi) { 8 | this.user_list = append(this.user_list, user) 9 | } 10 | 11 | func (this *ObjectStructure) HandleVisitor(visitor UserVisitor) { 12 | for _, user := range this.user_list { 13 | user.Accept(visitor) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Builder/Go/builder/Director.go: -------------------------------------------------------------------------------- 1 | package builder 2 | 3 | type Director struct { 4 | builder builder 5 | } 6 | 7 | func NewDirector(builder builder) *Director { 8 | return &Director{builder: builder} 9 | } 10 | 11 | func (this *Director) Construct(header string, body string, footer string) { 12 | this.builder.buildHeader(header) 13 | this.builder.buildBody(body) 14 | this.builder.buildFooter(footer) 15 | } 16 | -------------------------------------------------------------------------------- /Command/README.md: -------------------------------------------------------------------------------- 1 | ## 命令模式 2 | 3 | ### 概述 4 | 在开发中,我们经常需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么。我们希望做到只需在程序运行时指定具体的请求接收者即可,可以使用命令模式来进行设计,消除请求发送者与请求接收者彼此之间的耦合,让对象之间的调用关系更加灵活。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 使用一个音乐播放器的例子,有播放,暂停和停止播放三种命令。 11 | 12 | ### 总结与分析 13 | 命令模式的本质是对命令进行封装,将发出和执行命令的责任分割开。命令模式中的每一个命令都是一个操作,请求方发出请求,要求执行一个操作;接收的一方收到请求,并执行操作。 14 | -------------------------------------------------------------------------------- /Flyweight/PHP/test.php: -------------------------------------------------------------------------------- 1 | login("hhq"); 9 | $mgr->login("tom"); 10 | var_dump($mgr->hasPermit("hhq", "money", "look")); 11 | var_dump($mgr->hasPermit("tom", "money", "look")); 12 | -------------------------------------------------------------------------------- /Prototype/PHP/LifeArticle.php: -------------------------------------------------------------------------------- 1 | author->getName()); 6 | $this->setAuthor($author); 7 | } 8 | 9 | public function setAuthor($author) { 10 | $this->author = $author; 11 | } 12 | 13 | public function getAuthor() { 14 | return $this->author; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/README.md: -------------------------------------------------------------------------------- 1 | ## 工厂方法模式 2 | 3 | ### 概述 4 | 工厂方法就是将一个产品对应一个工厂,每个工厂只创建特定的产品。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 实现例子是手机的创建。分别使用三种工厂(IPhone、Android、Other)创建三种不同的手机。客户 11 | 12 | ### 总结与分析 13 | 工厂方法中,看起来跟普通创建类的实例没有区别,但是当类的构造非常复杂,直接实例化需要知道其构造方法,而且会造成很多重复的代码。工厂方法帮助我们将产品的“实现”从“使用”中解耦。如果增加产品或者改变产品的实现,工厂方法的Creator不会受到影响。这也是符合面向对象中对扩展开放,对修改关闭的原则。 14 | -------------------------------------------------------------------------------- /State/PHP/SpiteVoteState.php: -------------------------------------------------------------------------------- 1 | votes as $key => $vote) { 5 | if ($vote_manager->vote["user"] == $user) { 6 | unset($vote_manager->vote[$key]); 7 | break; 8 | } 9 | } 10 | 11 | echo "你有恶意刷票行为,取消投票资格\n"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/Go/abstractfactory/IPhoneFactory.go: -------------------------------------------------------------------------------- 1 | package abstractfactory 2 | 3 | type IPhoneFactory struct { 4 | IngredientFactory 5 | PhoneFactory 6 | } 7 | 8 | func (ipf *IPhoneFactory) CreateOS(name string) *IPhoneOS { 9 | return &IPhoneOS{&OS{Name: name}} 10 | } 11 | 12 | func (ipf *IPhoneFactory) CreateSpecial(content string) *IPhoneSpecial { 13 | return &IPhoneSpecial{&Special{Content: content}} 14 | } 15 | -------------------------------------------------------------------------------- /Memento/Go/memento/Memento.go: -------------------------------------------------------------------------------- 1 | package memento 2 | 3 | type Memento struct { 4 | temp_record string 5 | temp_time int 6 | } 7 | 8 | func NewMemento(temp_record string, temp_time int) *Memento { 9 | return &Memento{temp_record, temp_time} 10 | } 11 | 12 | func (this *Memento) GetTempRecord() string { 13 | return this.temp_record 14 | } 15 | 16 | func (this *Memento) GetTempTime() int { 17 | return this.temp_time 18 | } 19 | -------------------------------------------------------------------------------- /Visitor/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./visitor" 4 | 5 | func main() { 6 | add_point_visitor := &visitor.AddPointVisitor{} 7 | os := &visitor.ObjectStructure{} 8 | os.AddUser(visitor.NewVipUser("vip_hector")) 9 | os.AddUser(visitor.NewNormalUser("continue")) 10 | user_tom := visitor.NewNormalUser("tom") 11 | os.AddUser(user_tom) 12 | os.AddUser(user_tom) 13 | os.HandleVisitor(add_point_visitor) 14 | } 15 | -------------------------------------------------------------------------------- /Visitor/Go/visitor/User.go: -------------------------------------------------------------------------------- 1 | package visitor 2 | 3 | type User struct { 4 | name string 5 | point int 6 | } 7 | 8 | func NewUser(name string) *User { 9 | return &User{name, 0} 10 | } 11 | 12 | func (this *User) AddPoint(point int) { 13 | this.point += point 14 | } 15 | 16 | func (this *User) GetName() string { 17 | return this.name 18 | } 19 | 20 | func (this *User) GetPoint() int { 21 | return this.point 22 | } 23 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/Go/abstractfactory/AndroidFactory.go: -------------------------------------------------------------------------------- 1 | package abstractfactory 2 | 3 | type AndroidFactory struct { 4 | IngredientFactory 5 | PhoneFactory 6 | } 7 | 8 | func (af *AndroidFactory) CreateOS(name string) *AndroidOS { 9 | return &AndroidOS{&OS{Name: name}} 10 | } 11 | 12 | func (af *AndroidFactory) CreateSpecial(content string) *AndroidSpecial { 13 | return &AndroidSpecial{&Special{Content: content}} 14 | } 15 | -------------------------------------------------------------------------------- /Singleton/README.md: -------------------------------------------------------------------------------- 1 | ## 单例模式 2 | 3 | ### 概述 4 | 在开发中会遇到多个文件都需要创建某实例的情况,比如数据库类、缓存类等等。然而在多个文件中都实例化该类会导致多个实例存在,对于数据库这种对象,如果多次实例化会导致多次的网络开销,因此,在应用中共享数据库的实例可以减少网络开销。单例模式可以做到。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 将构造函数定义为私有的,保证单例类不能被实例化。再创建一个静态函数负责返回不用实例化也能返回实例化的对象,保证只有一个实例。 11 | 12 | ### 总结与分析 13 | 单例模式在开发中会经常遇到的,比如数据库连接。有一个要注意的地方就是线程安全,即多个线程共享同一个实例,可以在不同的线程环境下创建不同的实例来解决。 14 | -------------------------------------------------------------------------------- /Prototype/Go/prototype/Author.go: -------------------------------------------------------------------------------- 1 | package prototype 2 | 3 | type Author struct { 4 | name string 5 | } 6 | 7 | func NewAuthor(name string) *Author { 8 | return &Author{name} 9 | } 10 | 11 | func (this *Author) SetName(name string) { 12 | this.name = name 13 | } 14 | 15 | func (this *Author) GetName() string { 16 | return this.name 17 | } 18 | 19 | func (this *Author) Clone() *Author { 20 | return &Author{name: this.name} 21 | } 22 | -------------------------------------------------------------------------------- /TemplateMethod/README.md: -------------------------------------------------------------------------------- 1 | ## 模板方法模式 2 | 3 | ### 概述 4 | 模板方法定义了一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变算法结构的情况下,重新定义算法中的某些步骤。在开发中,当遇到某个算法的关键步骤及执行方案,而且执行方案中的某些步骤与具体的实现有关。则可以使用此模式解决。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 本例实现,使用含有接口和后台的Web开发的模板渲染,渲染的关键步骤是:获取数据->打包数据->渲染。可以发现,JSON和HTML的数据渲染的不同之处在于打包的地方,将打包抽取出来,放到子类中实现。 11 | 12 | ### 总结与分析 13 | 使用模板方式,将算法的某些步骤的实现细节交给子类,很好地遵循代码复用。 14 | -------------------------------------------------------------------------------- /Bridge/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./bridge" 4 | 5 | func main() { 6 | Impl := &bridge.MessageSMS{} 7 | m := &bridge.CommonMessage{&bridge.AbstractMessage{Impl}} 8 | m.SendMessage("hello", "tom") 9 | 10 | um := &bridge.UrgencyMessage{&bridge.AbstractMessage{Impl}} 11 | um.SendMessage("hello", "tom") 12 | 13 | sm := &bridge.SpecialUrgencyMessage{&bridge.AbstractMessage{Impl}} 14 | sm.SendMessage("hello", "tom") 15 | } 16 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/DivExpression.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | type DivExpression struct { 4 | *SymbolExpression 5 | } 6 | 7 | func NewDivExpression(Left Expression, Right Expression) *DivExpression { 8 | return &DivExpression{&SymbolExpression{Left: Left, Right: Right}} 9 | } 10 | 11 | func (this *DivExpression) Calculate() int { 12 | return this.SymbolExpression.Left.Calculate() / this.SymbolExpression.Right.Calculate() 13 | } 14 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/ModExpression.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | type ModExpression struct { 4 | *SymbolExpression 5 | } 6 | 7 | func NewModExpression(Left Expression, Right Expression) *ModExpression { 8 | return &ModExpression{&SymbolExpression{Left: Left, Right: Right}} 9 | } 10 | 11 | func (this *ModExpression) Calculate() int { 12 | return this.SymbolExpression.Left.Calculate() % this.SymbolExpression.Right.Calculate() 13 | } 14 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/MulExpression.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | type MulExpression struct { 4 | *SymbolExpression 5 | } 6 | 7 | func NewMulExpression(Left Expression, Right Expression) *MulExpression { 8 | return &MulExpression{&SymbolExpression{Left: Left, Right: Right}} 9 | } 10 | 11 | func (this *MulExpression) Calculate() int { 12 | return this.SymbolExpression.Left.Calculate() * this.SymbolExpression.Right.Calculate() 13 | } 14 | -------------------------------------------------------------------------------- /Mediator/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./mediator" 4 | 5 | func main() { 6 | controller := &mediator.Controller{} 7 | view := mediator.NewView(controller) 8 | model := mediator.NewModel(controller) 9 | controller.SetColleague(model, view) 10 | view.MakeAddRequest("tom") 11 | view.MakeAddRequest("amy") 12 | view.ShowUser() 13 | view.MakeDeleteRequest("tom") 14 | view.ShowUser() 15 | view.MakeDeleteRequest("aaa") 16 | } 17 | -------------------------------------------------------------------------------- /Memento/README.md: -------------------------------------------------------------------------------- 1 | ## 备忘录模式 2 | 3 | ### 概述 4 | 备忘者模式是在不破坏封装性的前提下捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将对象恢复到原先保存的状态。一个备忘录就是一个对象,它存储另一个对象在某个瞬间的内部状态,后者被称为备忘录的原发器。捕获对象状态的目的是为了在以后的某个时候,将该对象的状态恢复到备忘录所保存的状态。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 使用一个运动记录来实现备忘录模式。程序可以保存跑步的状态,然后在进行骑行或者健身时将跑步的记录添加进去完成当天的运动。 11 | 12 | ### 总结与分析 13 | 备忘录模式的本质是保存和恢复内部状态。在需要保存对象在某一个时刻的全部或者部分状态然后以后可以恢复该状态是可以使用备忘录模式。 14 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/PlusExpression.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | type PlusExpression struct { 4 | *SymbolExpression 5 | } 6 | 7 | func NewPlusExpression(Left Expression, Right Expression) *PlusExpression { 8 | return &PlusExpression{&SymbolExpression{Left: Left, Right: Right}} 9 | } 10 | 11 | func (this *PlusExpression) Calculate() int { 12 | return this.SymbolExpression.Left.Calculate() + this.SymbolExpression.Right.Calculate() 13 | } 14 | -------------------------------------------------------------------------------- /Visitor/PHP/ObjectStructure.php: -------------------------------------------------------------------------------- 1 | user_list[] = $user; 11 | } 12 | 13 | public function handleVisitor($visitor) { 14 | foreach($this->user_list as $user) { 15 | $user->accept($visitor); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/MinusExpression.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | type MinusExpression struct { 4 | *SymbolExpression 5 | } 6 | 7 | func NewMinusExpression(Left Expression, Right Expression) *MinusExpression { 8 | return &MinusExpression{&SymbolExpression{Left: Left, Right: Right}} 9 | } 10 | 11 | func (this *MinusExpression) Calculate() int { 12 | return this.SymbolExpression.Left.Calculate() - this.SymbolExpression.Right.Calculate() 13 | } 14 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/soy.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type Soy struct { 4 | *Condiment 5 | } 6 | 7 | func NewSoy(beverage beverage) *Soy { 8 | return &Soy{&Condiment{beverage: beverage, price: 1.2, description: "Soy"}} 9 | } 10 | 11 | func (self *Soy) Cost() float64 { 12 | return self.beverage.Cost() + self.price 13 | } 14 | 15 | func (self *Soy) GetDescription() string { 16 | return self.beverage.GetDescription() + " with " + self.description 17 | } 18 | -------------------------------------------------------------------------------- /Memento/PHP/test.php: -------------------------------------------------------------------------------- 1 | running(); 7 | $care_taker = new CareTaker(); 8 | $memento = $workout->createMemento(); 9 | $care_taker->saveMemento($memento); 10 | 11 | $workout->bicycle(); 12 | $workout->setMemento($care_taker->retriveMemento()); 13 | $workout->abdominal_ripper_x(); 14 | -------------------------------------------------------------------------------- /Observer/PHP/test.php: -------------------------------------------------------------------------------- 1 | registerObserver($observerA); 13 | $subject->registerObserver($observerB); 14 | 15 | $subject->setValue(5); 16 | ?> 17 | -------------------------------------------------------------------------------- /Visitor/PHP/AddPointVisitor.php: -------------------------------------------------------------------------------- 1 | addPoint(10); 5 | echo "给VIP{$vip_user->getName()}加10分,总分{$vip_user->getPoint()}分\n"; 6 | } 7 | 8 | public function addPointForNormal($normal_user) { 9 | $normal_user->addPoint(5); 10 | echo "给普通用户{$normal_user->getName()}加5分,总分{$normal_user->getPoint()}分\n"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Command/Go/command/Player.go: -------------------------------------------------------------------------------- 1 | package command 2 | 3 | type Player struct { 4 | state string 5 | } 6 | 7 | func NewPlayer() *Player { 8 | return &Player{""} 9 | } 10 | 11 | func (this *Player) Playing() { 12 | this.state = "playing" 13 | } 14 | 15 | func (this *Player) Pause() { 16 | this.state = "pause" 17 | } 18 | 19 | func (this *Player) Stop() { 20 | this.state = "stop" 21 | } 22 | 23 | func (this *Player) GetState() string { 24 | return this.state 25 | } 26 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/whip.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type Whip struct { 4 | *Condiment 5 | } 6 | 7 | func NewWhip(beverage beverage) *Whip { 8 | return &Whip{&Condiment{beverage: beverage, price: 0.9, description: "Whip"}} 9 | } 10 | 11 | func (self *Whip) Cost() float64 { 12 | return self.beverage.Cost() + self.price 13 | } 14 | 15 | func (self *Whip) GetDescription() string { 16 | return self.beverage.GetDescription() + " with " + self.description 17 | } 18 | -------------------------------------------------------------------------------- /Decorator/Go/decorator/mocha.go: -------------------------------------------------------------------------------- 1 | package decorator 2 | 3 | type Mocha struct { 4 | *Condiment 5 | } 6 | 7 | func NewMocha(beverage beverage) *Mocha { 8 | return &Mocha{&Condiment{beverage: beverage, price: 0.2, description: "Mocha"}} 9 | } 10 | 11 | func (self *Mocha) Cost() float64 { 12 | return self.beverage.Cost() + self.price 13 | } 14 | 15 | func (self *Mocha) GetDescription() string { 16 | return self.beverage.GetDescription() + " with " + self.description 17 | } 18 | -------------------------------------------------------------------------------- /Decorator/PHP/Soy.php: -------------------------------------------------------------------------------- 1 | description = " Soy"; 7 | $this->beverage = $beverage; 8 | } 9 | 10 | public function getDescription() { 11 | return $this->beverage->getDescription() . $this->description; 12 | } 13 | 14 | public function cost() { 15 | return $this->beverage->cost() + 8; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Memento/PHP/Memento.php: -------------------------------------------------------------------------------- 1 | temp_record = $temp_record; 9 | $this->temp_time = $temp_time; 10 | } 11 | 12 | public function getTempRecord() { 13 | return $this->temp_record; 14 | } 15 | 16 | public function getTempTime() { 17 | return $this->temp_time; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Adapter/Go/adapter/logger.go: -------------------------------------------------------------------------------- 1 | package adapter 2 | 3 | type Logger struct { 4 | log_id string 5 | ope_user_id string 6 | } 7 | 8 | func (lg *Logger) GetLogId() string { 9 | return lg.log_id 10 | } 11 | 12 | func (lg *Logger) SetLogId(log_id string) { 13 | lg.log_id = log_id 14 | } 15 | 16 | func (lg *Logger) GetOpeUserId() string { 17 | return lg.ope_user_id 18 | } 19 | 20 | func (lg *Logger) SetOpeUserId(ope_user_id string) { 21 | lg.ope_user_id = ope_user_id 22 | } 23 | -------------------------------------------------------------------------------- /Composite/PHP/NavigationComponent.php: -------------------------------------------------------------------------------- 1 | description = " Whip"; 7 | $this->beverage = $beverage; 8 | } 9 | 10 | public function getDescription() { 11 | return $this->beverage->getDescription() . $this->description; 12 | } 13 | 14 | public function cost() { 15 | return $this->beverage->cost() + 9.9; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /TemplateMethod/Go/templatemethod/JsonView.go: -------------------------------------------------------------------------------- 1 | package templatemethod 2 | 3 | import "encoding/json" 4 | 5 | type JsonView struct { 6 | *BaseView 7 | } 8 | 9 | type JData struct { 10 | Code string `json:"code"` 11 | Result string `json:"result"` 12 | } 13 | 14 | func (self *JsonView) PackData(data [2]string) string { 15 | var j_data JData 16 | j_data.Code = data[0] 17 | j_data.Result = data[1] 18 | js, _ := json.Marshal(j_data) 19 | return string(js[:len(js)]) 20 | } 21 | -------------------------------------------------------------------------------- /Adapter/PHP/test.php: -------------------------------------------------------------------------------- 1 | setLogId("111"); 10 | $logger->setOpeUserId("user_tom"); 11 | $logFileOperate_api = new LogFileOperate(""); 12 | $db_api = new LogAdapter($logFileOperate_api); 13 | $db_api->createLog($logger); 14 | ?> 15 | -------------------------------------------------------------------------------- /Decorator/PHP/Mocha.php: -------------------------------------------------------------------------------- 1 | description = ' Mocha'; 7 | $this->beverage = $beverage; 8 | } 9 | 10 | public function cost() { 11 | return $this->beverage->cost() + 10.3; 12 | } 13 | 14 | public function getDescription() { 15 | return $this->beverage->getDescription() . $this->description; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Adapter/PHP/LogFileOperate.php: -------------------------------------------------------------------------------- 1 | file_name = $file_name; 7 | } 8 | 9 | public function readLogFile() { 10 | $content = "test content from " . $this->file_name; 11 | return $content; 12 | } 13 | 14 | public function writeLogFile($content) { 15 | echo "writing $content\n"; 16 | } 17 | } 18 | ?> 19 | -------------------------------------------------------------------------------- /Facade/PHP/ServiceFacade.php: -------------------------------------------------------------------------------- 1 | store_dao = $store_dao; 8 | $this->goods_dao = $goods_dao; 9 | } 10 | 11 | public function goodsDetail() { 12 | return array( 13 | 'store_info' => $this->store_dao->info(), 14 | 'goods_info' => $this->goods_dao->info() 15 | ); 16 | } 17 | } 18 | ?> 19 | -------------------------------------------------------------------------------- /Strategy/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "./travel" 5 | 6 | func main() { 7 | strategyAir := new(travel.AirplaneStrategy) 8 | person := travel.SetStrategy(strategyAir) 9 | fmt.Printf(person.Travel()) 10 | 11 | strategyTra := new(travel.TrainStrategy) 12 | person = travel.SetStrategy(strategyTra) 13 | fmt.Printf(person.Travel()) 14 | 15 | strategyBi := new(travel.BicycleStrategy) 16 | person = travel.SetStrategy(strategyBi) 17 | fmt.Printf(person.Travel()) 18 | } 19 | -------------------------------------------------------------------------------- /State/README.md: -------------------------------------------------------------------------------- 1 | ## 状态模式 2 | 3 | ### 概述 4 | 当需要根据对象不同的状态执行不同的操作的时候,可以使用状态模式。状态模式允许对象在内部状态改变时改变它的行为,使得对象看起来好像修改了它的类。通过将每个状态封装进一个类,把以后需要做的任何改变局部化了。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 用状态模式实现投票系统。实现控制同一个用户只能投一票,如果一个用户反复投票,而且投票次数超过5次,则判定为恶意刷票,要取消该用户投票的资格,当然同时也要取消他所投的票;如果一个用户的投票次数超过8次,将进入黑名单,禁止再登录和使用系统。 11 | 12 | ### 总结与分析 13 | 状态模式的功能就是分离状态的行为,通过维护状态的变化,来调用不同状态对应的不同功能。也就是说,状态和行为是相关联的,它们的关系可以描述为:状态决定行为。状态模式的行为是平行性的,不可相互替换的;而策略模式的行为是平等性的,是可以相互替换的。 14 | -------------------------------------------------------------------------------- /Adapter/PHP/Logger.php: -------------------------------------------------------------------------------- 1 | log_id; 8 | } 9 | 10 | public function setLogId($log_id) { 11 | $this->log_id = $log_id; 12 | } 13 | 14 | public function getOpeUserId() { 15 | return $this->ope_user_id; 16 | } 17 | 18 | public function setOpeUserId($ope_user_id) { 19 | $this->ope_user_id = $ope_user_id; 20 | } 21 | } 22 | ?> 23 | -------------------------------------------------------------------------------- /Command/PHP/Player.php: -------------------------------------------------------------------------------- 1 | state = ""; 7 | } 8 | 9 | public function playing() { 10 | $this->state = "playing"; 11 | } 12 | 13 | public function pause() { 14 | $this->state = "pause"; 15 | } 16 | 17 | public function stop() { 18 | $this->state = "stop"; 19 | } 20 | 21 | public function getState() { 22 | return $this->state; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Visitor/Go/visitor/AddPointVisitor.go: -------------------------------------------------------------------------------- 1 | package visitor 2 | 3 | import "fmt" 4 | 5 | type AddPointVisitor struct { 6 | } 7 | 8 | func (this *AddPointVisitor) AddPointForVip(vip_user *VipUser) { 9 | vip_user.AddPoint(10) 10 | fmt.Printf("给VIP%s加10分,总分%d分\n", vip_user.GetName(), vip_user.GetPoint()) 11 | } 12 | 13 | func (this *AddPointVisitor) AddPointForNormal(normal_user *NormalUser) { 14 | normal_user.AddPoint(5) 15 | fmt.Printf("给普通用户%s加5分,总分%d分\n", normal_user.GetName(), normal_user.GetPoint()) 16 | } 17 | -------------------------------------------------------------------------------- /Visitor/README.md: -------------------------------------------------------------------------------- 1 | ## 访问者模式 2 | 3 | ### 概述 4 | 表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。访问器模式的本质就是预留通路,回调实现。 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 使用给用户添加积分的例子来实现访问者模式。用户系统中有普通用户和VIP用户,不同的用户添加的积分不一样,通过对象结构处理添加积分访问器来添加剂分。 11 | 12 | ### 总结与分析 13 | 访问者能够实现在不改变对象结构的情况下,就可以给对象结构中的类增加功能使用的是两次分发的技术。双分派意味着得到执行的操作决定于请求的种类和两个接收者的类型。Accept是一个两次分发操作,它的含义决定两个类型:访问器和具体元素。Accept通过采用“两次分发”技术将调用结果返回给访问器类。visit()方法定义在访问器类中,类层次结构中的某个类对象可以根据其类型调用合适的visit()方法。 14 | -------------------------------------------------------------------------------- /ChainOfResponsibility/PHP/test.php: -------------------------------------------------------------------------------- 1 | hello, i am tom.how are you?"; 9 | $filter_chain = new FilterChain(); 10 | $filter_chain->addFilter(new HTMLFilter())->addFilter(new LengthFilter()); 11 | $msg_processor = new MsgProcessor($msg, $filter_chain); 12 | echo $msg_processor->process() . "\n"; 13 | -------------------------------------------------------------------------------- /Prototype/README.md: -------------------------------------------------------------------------------- 1 | ## 原型模式 2 | 3 | ### 概述 4 | 用原型实例制定创建对象的类型,并通过拷贝这些原型创建新的对象。原型模式会要求对象实现一个可以“克隆”自身的接口,这样就可以通过拷贝或者是克隆一个实例对象本身来创建一个新的实例。如果把这个方法定义在接口上,看起来就像是通过接口来创建了新的接口对象。通过原型实例创建新的对象,不再需要关心这个实例本身的类型,也不关心它的具体实现,只要它实现了克隆自身的方法,就可以通过这个方法来获取新的对象,而无须再去通过new来创建。 5 | 6 | ### 结构图 7 |  8 | 9 | ### 实现 10 | 使用文章接口来实现原型模式。并使用深度克隆,即除了克隆按值传递的数据,还负责克隆引用类型的数据。 11 | 12 | ### 总结与分析 13 | 原型模式的本质是克隆生成对象。克隆是手段,目的是生成新的对象实例。原型模式可以用来解决“只知接口而不知实现的问题”。如果需要实例化的类是在运行时刻动态指定时,可以使用原型模式,通过原型来得到需要的实例。 14 | -------------------------------------------------------------------------------- /Command/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "./command" 5 | 6 | func main() { 7 | invoker := new(command.Invoker) 8 | player := command.NewPlayer() 9 | 10 | invoker.SetCommand(command.NewPlayCommand(player)) 11 | fmt.Printf("%s\n", invoker.Run()) 12 | 13 | invoker.SetCommand(command.NewPauseCommand(player)) 14 | fmt.Printf("%s\n", invoker.Run()) 15 | 16 | fmt.Printf("%s\n", invoker.Undo()) 17 | 18 | invoker.SetCommand(command.NewStopCommand(player)) 19 | fmt.Printf("%s\n", invoker.Run()) 20 | } 21 | -------------------------------------------------------------------------------- /Mediator/README.md: -------------------------------------------------------------------------------- 1 | ## 中介者模式 2 | 3 | ### 概述 4 | 中介者模式使用一个中介对象来封装一系列的对象交互。中介者使得各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。各个对象之间相互独立,中介者对象知道如何和其他所有的对象交互,当对象之间要相互引用时,就通过访问中介者对象。有点类似于找房子时候的中介。 5 | 6 | ### 结构图 7 |  8 | 9 | ### 实现 10 | 用MVC结构来实现中介者模式。Controller作为中介者对象,Model和View相互独立,Controller协调Model和View之间的交互。如Vdew发起增加用户请求,用Controller调用Model的增加用户的方法来实现该功能。 11 | 12 | ### 总结与分析 13 | 中介者模式的本质就是封装对象之间的交互。如果一个对象的操作会引起其他相关对象的变化,或者是某个操作需要引起其他对象的后续或连带操作,而这个对象又不希望自己来处理这些关系,那么可以使用中介者模式。 14 | -------------------------------------------------------------------------------- /Visitor/PHP/User.php: -------------------------------------------------------------------------------- 1 | name = $name; 8 | $this->point = 0; 9 | } 10 | 11 | public function addPoint($point) { 12 | $this->point += $point; 13 | } 14 | 15 | public function getName() { 16 | return $this->name; 17 | } 18 | 19 | public function getPoint() { 20 | return $this->point; 21 | } 22 | 23 | abstract function accept($visitor); 24 | } 25 | -------------------------------------------------------------------------------- /Adapter/PHP/LogAdapter.php: -------------------------------------------------------------------------------- 1 | logFileOperate = $logFileOperate; 7 | } 8 | 9 | public function createLog($logger) { 10 | $content = $this->logFileOperate->readLogFile(); 11 | $this->logFileOperate->writeLogFile("id: " . $logger->getLogId() . ";ope_user_id: " . $logger->getOpeUserId() . ";content: " . $content); 12 | echo "write into db\n"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ChainOfResponsibility/Go/chain/FilterChain.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | type FilterChain struct { 4 | filters []Filter 5 | } 6 | 7 | func NewFilterChain() *FilterChain { 8 | return &FilterChain{} 9 | } 10 | 11 | func (this *FilterChain) AddFilter(filter Filter) *FilterChain { 12 | this.filters = append(this.filters, filter) 13 | return this 14 | } 15 | 16 | func (this *FilterChain) HandleFilter(str string) string { 17 | for _, filter := range this.filters { 18 | str = filter.HandleFilter(str) 19 | } 20 | 21 | return str 22 | } 23 | -------------------------------------------------------------------------------- /Adapter/Go/adapter/LogFileOperate.go: -------------------------------------------------------------------------------- 1 | package adapter 2 | 3 | import "fmt" 4 | 5 | type LogFileOperate struct { 6 | LogFileOperateAPI 7 | file_name string 8 | } 9 | 10 | func NewLogFileOperate(file_name string) *LogFileOperate{ 11 | return &LogFileOperate{file_name: file_name} 12 | } 13 | 14 | func (this *LogFileOperate) ReadLogFile() string { 15 | content := "test content from " + this.file_name 16 | return content 17 | } 18 | 19 | func (this *LogFileOperate) WriteLogFile(content string) { 20 | fmt.Printf("Writing %s\n", content) 21 | } 22 | -------------------------------------------------------------------------------- /Builder/Go/builder/TextBuilder.go: -------------------------------------------------------------------------------- 1 | package builder 2 | 3 | type TextBuilder struct { 4 | content string 5 | } 6 | 7 | func (this *TextBuilder) buildHeader(header string) { 8 | this.content += "header: " + header + "\n" 9 | } 10 | 11 | func (this *TextBuilder) buildBody(body string) { 12 | this.content += "body: " + body + "\n" 13 | } 14 | 15 | func (this *TextBuilder) buildFooter(footer string) { 16 | this.content += "footer: " + footer + "\n" 17 | } 18 | 19 | func (this *TextBuilder) GetResult() string { 20 | return this.content 21 | } 22 | -------------------------------------------------------------------------------- /ChainOfResponsibility/PHP/FilterChain.php: -------------------------------------------------------------------------------- 1 | filters = array(); 7 | } 8 | 9 | public function addFilter($filter) { 10 | array_push($this->filters, $filter); 11 | return $this; 12 | } 13 | 14 | public function handleFilter($str) { 15 | foreach ($this->filters as $filter) { 16 | $str = $filter->handleFilter($str); 17 | } 18 | 19 | return $str; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Mediator/PHP/View.php: -------------------------------------------------------------------------------- 1 | getMeditor()->addUser($user); 6 | } 7 | 8 | public function showUser() { 9 | print_r($this->getMeditor()->getUserList()); 10 | } 11 | 12 | public function makeDeleteRequest($user) { 13 | echo "发起删除用户{$user}请求\n"; 14 | $this->getMeditor()->deleteUser($user); 15 | } 16 | 17 | public function showResult($result) { 18 | echo $result; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Builder/PHP/TextBuilder.php: -------------------------------------------------------------------------------- 1 | content .= "Text header: " . $header . "\n"; 7 | } 8 | 9 | public function buildBody($body) { 10 | $this->content .= "Text body: " . $body . "\n"; 11 | } 12 | 13 | public function buildFooter($footer) { 14 | $this->content .= "Text footer: " . $footer . "\n"; 15 | } 16 | 17 | public function getResult() { 18 | return $this->content; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Decorator/README.md: -------------------------------------------------------------------------------- 1 | ## 装饰者模式 2 | 3 | ### 概述 4 | 当对象需要添加一些功能,比如在表单的组件添加验证功能,为咖啡添加配料,为窗口添加滚动条等等.此时如果使用继承的话,会产生很多子类,不好管理,而且,在项目越来越大的时候会出现类爆炸.使用装饰者模式,使用组合的形式构造对象,比使用继承更加灵活简单,也更加容易管理. 5 | 6 | ### 结构 7 |  8 | 9 | ### 实现 10 | 此处实现为咖啡添加配料.有咖啡材料,现调制摩卡咖啡等.使用Beverage抽象类,咖啡和配料分别继承Beverage类,并实现里面的抽象方法Cost和GetDecription.配料的构造方法传入咖啡类,通过在配料的构造函数里组合配料与咖啡原料实现装饰者模式.每个配料(装饰者)都有(包装)一个组件,在装饰者里保存一个原料的引用就能实现咖啡被配料包(装饰)起来. 11 | 12 | ### 总结与分析 13 | 装饰者模式采用组合的构建方式,大大减少了类的数量,也打破了扩展功能一定要使用继承的思维惯性.但是装饰者模式会产生过多的小类,过度地使用会让程序变得更复杂. 14 | -------------------------------------------------------------------------------- /Builder/Go/builder/XmlBuilder.go: -------------------------------------------------------------------------------- 1 | package builder 2 | 3 | type XmlBuilder struct { 4 | content string 5 | } 6 | 7 | func (this *XmlBuilder) buildHeader(header string) { 8 | this.content += "