├── 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 | ![解释器模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/解释器模式结构图.png) 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 | ![迭代器模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/迭代器模式结构图.jpg) 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 | ![组合模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/组合模式结构图.jpg) 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 | ![职责链模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/职责连模式结构图.png) 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 | ![适配器模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/适配器模式结构图.jpg) 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 | ![抽象工厂模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/抽象工厂模式结构图.jpg) 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 | ![命令模式结构图.jpg](http://7u2eqw.com1.z0.glb.clouddn.com/命令模式结构图.jpg) 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 | ![工厂方法模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/工厂方法模式结构图.png) 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 | ![单例模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/单例模式结构图.png) 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 | ![模板方法模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/模板方法模式结构图.jpg) 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 | ![备忘录模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/备忘录模式结构图.png) 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 | ![状态模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/状态模式结构图.jpg) 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 | ![访问者模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/访问者模式结构图.png) 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 | ![原型模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/原型模式结构图.png) 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 | ![中介者模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/中介者模式结构图.png) 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 | ![装饰者模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/装饰者模式结构图.jpg) 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 += "
" + header + "
\n" 9 | } 10 | 11 | func (this *XmlBuilder) buildBody(body string) { 12 | this.content += "" + body + "\n" 13 | } 14 | 15 | func (this *XmlBuilder) buildFooter(footer string) { 16 | this.content += "\n" 17 | } 18 | 19 | func (this *XmlBuilder) GetResult() string { 20 | return this.content 21 | } 22 | -------------------------------------------------------------------------------- /Iterator/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./iterator" 4 | import "fmt" 5 | 6 | func main() { 7 | goods_list := new(iterator.GoodsList) 8 | goods_list.AddGoods(iterator.NewGoods("tshirt")) 9 | goods_list.AddGoods(iterator.NewGoods("jean")) 10 | goods_list.AddGoods(iterator.NewGoods("phone")) 11 | goods_list.AddGoods(iterator.NewGoods("cup")) 12 | 13 | for goods_iterator := iterator.NewGoodsIterator(goods_list);goods_iterator.Valid(); { 14 | fmt.Printf("%s\n", goods_iterator.Current().GetName()) 15 | goods_iterator.Next() 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Adapter/Go/adapter/LogAdapter.go: -------------------------------------------------------------------------------- 1 | package adapter 2 | 3 | import "fmt" 4 | 5 | type LogAdapter struct { 6 | LogFileOperateAPI 7 | *LogFileOperate 8 | } 9 | 10 | func NewLogAdapter(logFileOperate *LogFileOperate) *LogAdapter { 11 | return &LogAdapter{LogFileOperate: logFileOperate} 12 | } 13 | 14 | func (this *LogAdapter) CreateLog(lg *Logger) { 15 | content := this.LogFileOperate.ReadLogFile() 16 | this.LogFileOperate.WriteLogFile("id: " + lg.GetLogId() + ";ope_user_id: " + lg.GetOpeUserId() + ";content: " + content); 17 | fmt.Printf("Write into db\n"); 18 | } 19 | -------------------------------------------------------------------------------- /Bridge/RAEDME.md: -------------------------------------------------------------------------------- 1 | ## 桥接模式 2 | 3 | ### 概述 4 | 桥接模式将抽象部分与它的实现部分分离,使他们都可以独立地变化。通俗地说,桥接就是在不同的东西之间搭一个桥,让它们能够连接起来,可以相互通讯和使用。在桥接模式中的桥接是在被分离的抽象部分和实现部分之间搭一个桥。为了达到让抽象部分和实现部分分离开,而且在抽象部分实现的时候,还是需要使用具体的实现,可以使用桥接模式来实现。这里的桥接,就是让抽象部分拥有实现部分的接口对象,就桥接上了。 5 | 6 | ### 结构 7 | ![桥接模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/桥接模式结构图.png) 8 | 9 | ### 实现 10 | 使用发送信息的例子来实现桥接模式。信息的发送方式如:手机信息、普通信息、Email信息作为抽象部分,信息的分类如:普通信息、紧急信息、加急信息作为具体实现部分。 11 | 12 | ### 总结与分析 13 | 桥接模式是用来解决有两个变化纬度的情况下,如何灵活地扩展功能的一个很好的方案。其实,桥接模式主要是把继承改成了使用对象组合,从而把两个纬度分开,让每一个纬度单独地去变化,最后通过对象组合的方式,把两个纬度组合起来。桥接模式也从侧面体现了使用对象组合的方式比继承要来得更灵活。 14 | -------------------------------------------------------------------------------- /Builder/PHP/XmlBuilder.php: -------------------------------------------------------------------------------- 1 | content .= "
" . $header . "
\n"; 7 | } 8 | 9 | public function buildBody($body) { 10 | $this->content .= "" . $body . "\n"; 11 | } 12 | 13 | public function buildFooter($footer) { 14 | $this->content .= "\n"; 15 | } 16 | 17 | public function getResult() { 18 | return $this->content; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Mediator/PHP/test.php: -------------------------------------------------------------------------------- 1 | setColleague($model, $view); 12 | $view->makeAddRequest('tom'); 13 | $view->makeAddRequest('amy'); 14 | $view->showUser(); 15 | $view->makeDeleteRequest("tom"); 16 | $view->showUser(); 17 | $view->makeDeleteRequest("aaa"); 18 | -------------------------------------------------------------------------------- /Builder/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./builder" 4 | import "fmt" 5 | 6 | func main() { 7 | header := "title->test" 8 | body := "builder" 9 | footer := "end" 10 | 11 | text_builder := &builder.TextBuilder{} 12 | text_director := builder.NewDirector(text_builder) 13 | text_director.Construct(header, body, footer) 14 | fmt.Println(text_builder.GetResult()) 15 | 16 | xml_builder := &builder.XmlBuilder{} 17 | xml_director := builder.NewDirector(xml_builder) 18 | xml_director.Construct(header, body, footer) 19 | fmt.Println(xml_builder.GetResult()) 20 | } 21 | -------------------------------------------------------------------------------- /Observer/Go/observer/concreteSubject.go: -------------------------------------------------------------------------------- 1 | package observer 2 | 3 | type ConcreteSubject struct { 4 | value string 5 | observers []Observer 6 | } 7 | 8 | func (cs *ConcreteSubject) RegisterObserver(ob Observer) { 9 | cs.observers = append(cs.observers, ob) 10 | } 11 | 12 | func (cs *ConcreteSubject) Notify() { 13 | for _, observer := range cs.observers { 14 | observer.Update(cs.value) 15 | } 16 | } 17 | 18 | func (cs *ConcreteSubject) SetValue(val string) { 19 | cs.value = val 20 | cs.Notify() 21 | } 22 | 23 | func (cs *ConcreteSubject) GetValue() string { 24 | return cs.value 25 | } 26 | -------------------------------------------------------------------------------- /Command/PHP/test.php: -------------------------------------------------------------------------------- 1 | setCommand($playCommand); 14 | $invoker->run(); 15 | $invoker->undo(); 16 | $invoker->setCommand($pauseCommand); 17 | $invoker->run(); 18 | $invoker->undo(); 19 | ?> 20 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "./factorymethod" 6 | ) 7 | 8 | func main() { 9 | iphoneFactory := &factorymethod.IPhoneFactory{} 10 | androidFactory := &factorymethod.AndroidFactory{} 11 | otherFactory := &factorymethod.OtherFactory{} 12 | 13 | iphone := iphoneFactory.CreatePhone() 14 | fmt.Printf("Get phone %s \n", iphone.GetName()) 15 | 16 | android := androidFactory.CreatePhone() 17 | fmt.Printf("Get phone %s \n", android.GetName()) 18 | 19 | other := otherFactory.CreatePhone() 20 | fmt.Printf("Get phone %s \n", other.GetName()) 21 | } 22 | -------------------------------------------------------------------------------- /Proxy/README.md: -------------------------------------------------------------------------------- 1 | ## 代理模式 2 | 3 | ### 概述 4 | 代理模式为其他对象提供一种代理以控制对这个对象的访问。对一个对象进行访问控制的原因是为了只有在我们确实需要这个对象时才对它进行创建和初始化。 5 | 6 | ### 结构 7 | ![代理模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/代理模式结构图.jpg) 8 | 9 | ### 实现 10 | 考虑一个数据库操作。当需要发请求让数据库查询数据的时候,需要先获得数据库连接来初始化系统。当软件中存在很多这样的需要获得链接才能进行下一步的操作时,会消耗很多时间。将消耗资源最多的方法使用代理模式分离,可以加快系统的启动速度。而在用户真正做查询操作时再由代理类单独去加载真实的数据库查询类,而非真实的数据库查询类,而且代理类什么都没有做。 11 | 12 | ### 总结与分析 13 | 代理,就是我们让别人帮我们做事,我们提供必要的信息,代理人做完事情后可能会也可能不会告诉我们。代理模式跟装饰器模式很相似,但装饰器为对象添加一个或多个功能,而代理则控制对对象的访问。代理模式还与适配器模式有点相似,适配器模式为它所适配的对象提供了一个不同的接口。相反,代理提供了与它的实体相同的接口。然而,用于访问保护的代理可能会拒绝执行实体会执行的操作,因此,代理的接口实际上可能只是实体接口的一个子集。 14 | -------------------------------------------------------------------------------- /Visitor/PHP/test.php: -------------------------------------------------------------------------------- 1 | addUser(new VipUser("vip_hector")); 13 | $os->addUser(new NormalUser("continue")); 14 | $user_tom = new NormalUser("tom"); 15 | $os->addUser($user_tom); 16 | $os->addUser($user_tom); 17 | 18 | $os->handleVisitor($add_point_visitor); 19 | -------------------------------------------------------------------------------- /Facade/README.md: -------------------------------------------------------------------------------- 1 | ## 外观模式 2 | 3 | ### 概述 4 | 外观模式提供一个统一的接口,用来访问子系统中的一群接口。如果项目中有一个类需要使用很多的类来实现一个功能,可以使用外观模式。外观模式定义了一个高层接口,让子系统更容易使用。 5 | 6 | ### 结构 7 | ![外观模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/外观模式结构图.png) 8 | 9 | ### 实现 10 | 现在的Web开发中,大多采用MVC(Model-View-Controller)模式。很多时候都是Controller从Model拿到数据后处理返回给View这样的过程,这样做往往逻辑有点乱,其实可以考虑在Controller和Model之间加一层Service,数据的处理都放在Service里面,这样就能大大提高程序的可维护性。可以用外观模式实现Service,Service中的类为将Model中的一系列接口提供一个更高层的接口,是Controller和Model之间的数据交互更容易地使用。 11 | 12 | ### 总结与分析 13 | 外观模式没有封装子系统的类,外观模式只是提供简化的接口。所以客户依然可以直接使用子系统的类。外观模式和适配器模式可以包装许多类,两者区别在于意图。外观模式的意图是简化接口,而适配器模式的意图是将接口转换成不同接口以符合客户的期望。 14 | -------------------------------------------------------------------------------- /Builder/README.md: -------------------------------------------------------------------------------- 1 | ## 生成器模式 2 | 3 | ### 概述 4 | 生成器模式将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示。生成器模式的主要功能是构建复杂的产品,而且是细化地、分步骤地构建产品,也就是说生成器模式重在一步一步解决构建复杂对象的问题。 5 | 6 | ### 结构 7 | ![生成器模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/生成器模式结构图.png) 8 | 9 | ### 实现 10 | 使用文件的导出来实现生成器模式。文件的导出有普通文本和xml等文件格式。生成器作为一个接口,不同的具体生成器具体实现接口的方法。还有一个指导者负责整体构建的算法部分,是相对不变的部分。 11 | 12 | ### 总结与分析 13 | 生成器模式构建对象的过程是统一的、固定不变的,变化的部分放到生成器部分了,只要配置不同的生成器,那么同样的构建过程,就能构建出不同的产品来。生成器模式的重心在于分离构建方法和具体的构造实现,从而使得构建算法可以重用。具体的构造实现可以很方便地扩展和切换,从而可以灵活地组合来构造出不同的产品对象。生成器模式跟模板方法模式很像,但是模板方法模式主要是用来定义算法的骨架,把算法中某些步骤延迟到子类中实现。生成器模式是用“指导者”来定义整体的构建算法,把算法中某些涉及到具体部件对象的创建和装配的功能,委托给具体的生成器来实现。 14 | -------------------------------------------------------------------------------- /Prototype/Go/prototype/TechArticle.go: -------------------------------------------------------------------------------- 1 | package prototype 2 | 3 | type TechArticle struct { 4 | title string 5 | author *Author 6 | } 7 | 8 | func (this *TechArticle) Clone() ArticleApi { 9 | return &TechArticle{title: this.title, author: this.author} 10 | } 11 | 12 | func (this *TechArticle) SetTitle(title string) { 13 | this.title = title 14 | } 15 | 16 | func (this *TechArticle) GetTitle() string { 17 | return this.title 18 | } 19 | 20 | func (this *TechArticle) SetAuthor(author *Author) { 21 | this.author = author 22 | } 23 | 24 | func (this *TechArticle) GetAuthor() *Author { 25 | return this.author 26 | } 27 | -------------------------------------------------------------------------------- /Iterator/PHP/test.php: -------------------------------------------------------------------------------- 1 | addGoods(new Goods("t-shirt")); 8 | $goods_list->addGoods(new Goods("cup")); 9 | $goods_list->addGoods(new Goods("jean")); 10 | $goods_list->addGoods(new Goods("phone")); 11 | $goods_list->addGoods(new Goods("keyboard")); 12 | 13 | $goods_iterator = new GoodsIterator($goods_list); 14 | 15 | while ($goods_iterator->valid()) { 16 | echo $goods_iterator->current()->getName() . "\n"; 17 | $goods_iterator->next(); 18 | } 19 | -------------------------------------------------------------------------------- /Composite/Go/composite/BaseNavigation.go: -------------------------------------------------------------------------------- 1 | package composite 2 | 3 | import "fmt" 4 | 5 | type BaseNavigation struct { 6 | Name string 7 | navigationcomponent 8 | } 9 | 10 | func (bn *BaseNavigation) Add(navigationcomponent navigationcomponent) { 11 | fmt.Printf("Unsupported operation\n") 12 | } 13 | 14 | func (bn *BaseNavigation) Remove(navigationcomponent navigationcomponent) { 15 | fmt.Printf("Unsupported operation\n") 16 | } 17 | 18 | func (bn *BaseNavigation) GetChild() string { 19 | fmt.Printf("Unsupported operation\n") 20 | return "" 21 | } 22 | 23 | func (this *BaseNavigation) GetName() string { 24 | return this.Name 25 | } 26 | -------------------------------------------------------------------------------- /Strategy/PHP/test.php: -------------------------------------------------------------------------------- 1 | setStrategy($trainStrategy); 12 | $person->travel(); 13 | 14 | $bicycleStrategy = new BicycleStrategy(); 15 | $person->setStrategy($bicycleStrategy); 16 | $person->travel(); 17 | 18 | $airplaneStrategy = new AirplaneStrategy(); 19 | $person->setStrategy($airplaneStrategy); 20 | $person->travel(); 21 | 22 | ?> 23 | -------------------------------------------------------------------------------- /Builder/PHP/test.php: -------------------------------------------------------------------------------- 1 | test"; 8 | $body = "test builder"; 9 | $footer = "end"; 10 | 11 | $text_builder = new TextBuilder(); 12 | $text_director = new Director($text_builder); 13 | $text_director->construct($header, $body, $footer); 14 | 15 | $xml_builder = new XmlBuilder(); 16 | $xml_director = new Director($xml_builder); 17 | $xml_director->construct($header, $body, $footer); 18 | echo $text_builder->getResult(); 19 | echo $xml_builder->getResult(); 20 | -------------------------------------------------------------------------------- /Mediator/Go/mediator/Controller.go: -------------------------------------------------------------------------------- 1 | package mediator 2 | 3 | type Controller struct { 4 | model *Model 5 | view *View 6 | } 7 | 8 | func (this *Controller) SetColleague(model *Model, view *View) { 9 | this.model = model 10 | this.view = view 11 | } 12 | 13 | func (this *Controller) AddUser(user string) { 14 | this.model.AddUser(user) 15 | } 16 | 17 | func (this *Controller) GetUserList() []string { 18 | return this.model.GetUserList() 19 | } 20 | 21 | func (this *Controller) DeleteUser(user string) { 22 | this.model.DeleteUser(user) 23 | } 24 | 25 | func (this *Controller) ShowResult(result string) { 26 | this.view.ShowResult(result) 27 | } 28 | -------------------------------------------------------------------------------- /Observer/README.md: -------------------------------------------------------------------------------- 1 | ##观察者模式 2 | 3 | ### 概述 4 | 观察者模式,一个比较好理解的类比就是博客订阅。被订阅的博客是主体,而订阅了该博客的用户是客体,或者称为观察者。当主体发生改变,比如主体有新的文章,那么就需要通知所有的客体,使得客体能得到通知并更新订阅的内容。而客体是通过一种“注册订阅”的功能来告诉主体它想当一个观察者,意思就是告诉主体,“我对你的数据感兴趣,一有变化请通知我”。当然,客体也可以“取消订阅”,然后不再获得主体的通知。关于客体的一切,主体只知道客体实现了某个接口。主体不需要知道客体的具体类是谁、做了什么。任何时候都可以增加新的客体,而且主体不会受到影响。因为它们两者是松耦合的。要做到主体和客体之间相互独立地被复用,可以采用观察者模式。观察者就定义了对象之间的一对多依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。 5 | 6 | ### 结构 7 | ![观察者模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/观察者模式结构图.jpg) 8 | 9 | ### 实现 10 | 设计一个Subject接口和Observer接口。实例化两个Observer。两个Observer分别订阅Subject,然后在Subject实例的内容发生改变时,订阅了Subject的Observer就可以得到通知。 11 | 12 | ### 总结与分析 13 | 通过观察者模式,把对象之间的一对多依赖关系变得松散,程序变得易维护和更有弹性,更能应对变化。 14 | -------------------------------------------------------------------------------- /Flyweight/Go/flyweight/FlyweightFactory.go: -------------------------------------------------------------------------------- 1 | package flyweight 2 | 3 | type FlyweightFactory struct { 4 | fmMap map[string]*AuthorizationFactory 5 | } 6 | 7 | var instance *FlyweightFactory 8 | 9 | func GetInstance() *FlyweightFactory { 10 | if instance == nil { 11 | instance = &FlyweightFactory{} 12 | } 13 | 14 | return instance 15 | } 16 | 17 | func (this *FlyweightFactory) GetFlyweight(key string) *AuthorizationFactory { 18 | if this.fmMap == nil { 19 | this.fmMap = make(map[string]*AuthorizationFactory) 20 | } 21 | 22 | if _, ok := this.fmMap[key]; !ok { 23 | this.fmMap[key] = NewAuthorizationFactory(key) 24 | } 25 | 26 | return this.fmMap[key] 27 | } 28 | -------------------------------------------------------------------------------- /Mediator/PHP/Controller.php: -------------------------------------------------------------------------------- 1 | model = $model; 9 | $this->view = $view; 10 | } 11 | 12 | public function addUser($user) { 13 | $this->model->addUser($user); 14 | } 15 | 16 | public function getUserList() { 17 | return $this->model->getUserList(); 18 | } 19 | 20 | public function deleteUser($user) { 21 | $this->model->deleteUser($user); 22 | } 23 | 24 | public function showResult($result) { 25 | $this->view->showResult($result); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Interpreter/PHP/test.php: -------------------------------------------------------------------------------- 1 | init($statement); 18 | 19 | $result = $calculator->compute(); 20 | 21 | echo $statement . " = " . $result . "\n"; 22 | -------------------------------------------------------------------------------- /Prototype/Go/prototype/LifeArticle.go: -------------------------------------------------------------------------------- 1 | package prototype 2 | 3 | type LifeArticle struct { 4 | title string 5 | author *Author 6 | } 7 | 8 | func (this *LifeArticle) Clone() ArticleApi { 9 | life_article := &LifeArticle{title: this.title} 10 | life_article.SetAuthor(this.author.Clone()) 11 | return life_article 12 | } 13 | 14 | func (this *LifeArticle) SetTitle(title string) { 15 | this.title = title 16 | } 17 | 18 | func (this *LifeArticle) GetTitle() string { 19 | return this.title 20 | } 21 | 22 | func (this *LifeArticle) SetAuthor(author *Author) { 23 | this.author = author 24 | } 25 | 26 | func (this *LifeArticle) GetAuthor() *Author { 27 | return this.author 28 | } 29 | -------------------------------------------------------------------------------- /Flyweight/PHP/FlyweightFactory.php: -------------------------------------------------------------------------------- 1 | fwMap = array(); 9 | } 10 | 11 | public static function getInstance() { 12 | if (self::$instance === null) { 13 | self::$instance = new self(); 14 | } 15 | 16 | return self::$instance; 17 | } 18 | 19 | public function getFlyweight($key) { 20 | if (!isset(self::$instance->fwMap[$key])) { 21 | self::$instance->fwMap[$key] = new AuthorizationFlyweight($key); 22 | } 23 | 24 | return self::$instance->fwMap[$key]; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Prototype/PHP/test.php: -------------------------------------------------------------------------------- 1 | setTitle("test"); 8 | $author_hector = new Author("hector"); 9 | $life_article->setAuthor($author_hector); 10 | 11 | $article = clone $life_article; 12 | $article->setTitle("Programmer life"); 13 | var_dump($article); 14 | var_dump($life_article); 15 | 16 | echo $article->getTitle() . "\n"; 17 | $article->getAuthor()->setName("haha"); 18 | echo $article->getAuthor()->getName() . "\n"; 19 | echo $life_article->getAuthor()->getName() . "\n"; 20 | echo $life_article->getTitle() . "\n"; 21 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "./abstractfactory" 5 | 6 | func main() { 7 | iPhoneFactory := new(abstractfactory.IPhoneFactory) 8 | iphone_os := iPhoneFactory.CreateOS("IOS") 9 | fmt.Printf("Creating %s...\n", iphone_os.Create()) 10 | iphone_special := iPhoneFactory.CreateSpecial("siri") 11 | fmt.Printf("Creating %s...\n", iphone_special.Create()) 12 | 13 | androidFactory := new(abstractfactory.AndroidFactory) 14 | android_os := androidFactory.CreateOS("Android") 15 | fmt.Printf("Creating %s...\n", android_os.Create()) 16 | android_special := androidFactory.CreateSpecial("nfc") 17 | fmt.Printf("Creating %s...\n", android_special.Create()) 18 | } 19 | -------------------------------------------------------------------------------- /Composite/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./composite" 4 | import "fmt" 5 | 6 | func main() { 7 | store_navigation := composite.NewParentNavigation("store") 8 | 9 | nike := composite.NewChildNavigation("nike") 10 | adidas := composite.NewChildNavigation("adidas") 11 | new_balance := composite.NewChildNavigation("new balance") 12 | asscis := composite.NewChildNavigation("asscis") 13 | 14 | store_navigation.Add(nike) 15 | store_navigation.Add(adidas) 16 | store_navigation.Add(new_balance) 17 | store_navigation.Add(asscis) 18 | 19 | fmt.Printf("%s\n", store_navigation.GetChild()) 20 | 21 | food := composite.NewChildNavigation("food"); 22 | food.Add(composite.NewChildNavigation("kfc")); 23 | } 24 | -------------------------------------------------------------------------------- /Flyweight/README.md: -------------------------------------------------------------------------------- 1 | ## 享元模式 2 | 3 | ### 概述 4 | 在程序中可能需要根据某种条件创建大量的对象,比如权限对象需要在每一次查询的时候创建用户对象,如果用户多了,那么权限对象就多了。使用享元模式,可以每个权限对象只创建一次,第二次用户再请求的时候可以直接复用第一次创建的对象。享元模式就是运用共享技术有效地支持大量细粒度的对象。将程序中不变且重复出现的数据分离出来共享,称之为享元,通过共享享元对象来减少对内存的占用。把外部状态分离出来,放到外部,让应用在使用的时候进行维护,并在需要的时候传递给享元对象使用。 5 | 6 | ### 结构 7 | ![享元模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/享元模式结构图.jpg) 8 | 9 | ### 实现 10 | 使用用户权限管理来实现享元模式。因为在用户权限中,用户的数据是重复出现的,当在验证用户权限的时候要将用户数据授权到具体对象,这时候,就需要很多的对象,而每个对象包含的数据都是很少的,这就有了很多的细粒度对象,而且有大量的重复数据。用一个享元工厂来管理享元,控制对内部状态的共享,并且让外部能简单地使用共享数据。将安全实体(即用户)和权限的描述定义为享元,而和它们结合的人员数据作为外部数据。 11 | 12 | ### 总结与分析 13 | 享元模式的重点在于分离变与不变。把一个对象的状态分为内部状态和外部状态,内部状态是不变的,外部状态是可变的。通过共享不变的部分,减少对象数量并节约内存的目的。在享元对象需要的时候,可以从外部闯入外部状态给共享的对象,共享对象会在功能处理的时候,使用自己内部的状态和外部的状态。 14 | -------------------------------------------------------------------------------- /Strategy/README.md: -------------------------------------------------------------------------------- 1 | ## 策略模式 2 | 3 | ### 概述 4 | 在开发过程中,我们会遇到使用多种算法或策略实现某一功能。比如要实现用户的登录,用户可以通过表单提交,也可以发起AJAX请求。这时候我们就要为登录功能编写两种不同的算法了。在实现的时候通常会在同一个类里面编写多种算法,然后使用if...else...或者case等条件判断语句来进行选择执行哪种算法。那么问题来了,假如有一天,需要增加几个登录的方案,那么就要在类里面编写更多的方法,还需要修改条件判断语句,这样的类比较复杂,难以维护。策略模式就是定义了算法族,分别封装起来,让它们之间可以相互替换,策略模式让算法的变化独立于使用算法的客户。 5 | 6 | ### 结构 7 | ![策略模式结构图](http://7u2eqw.com1.z0.glb.clouddn.com/策略模式结构.jpg) 8 | 9 | > Context类维护一个对Strategy对下的引用,可定义一个结构让Strategy访问它的数据。 10 | 11 | > Strategy类定义所有支持的算法的公共接口。 12 | 13 | > ConcreteStrategy以Strategy接口实现某种具体的算法 14 | 15 | ### 实现 16 | 以出行旅游为例,我们可以有几个策略可以考虑:可以骑自行车,搭火车,搭飞机。每个策略都可以达到去旅游的目的,但是它们使用了不同的资源。具体实现看代码。 17 | 18 | ### 总结与分析 19 | > 策略模式是对算法的封装。通常会把一系列算法封装到一系列的作为抽象策略类的子类里面 20 | 21 | > 策略模式是针对接口编程 22 | -------------------------------------------------------------------------------- /Composite/PHP/test.php: -------------------------------------------------------------------------------- 1 | add($nike); 14 | $store_navigation->add($adidas); 15 | $store_navigation->add($new_balance); 16 | $store_navigation->add($assics); 17 | 18 | var_dump($store_navigation->getChild()); 19 | 20 | $food = new ChildNavigation('food'); 21 | $food->add(new ChildNavigation('kfc')); 22 | -------------------------------------------------------------------------------- /Command/Go/command/PlayCommand.go: -------------------------------------------------------------------------------- 1 | package command 2 | 3 | type PlayCommand struct { 4 | command 5 | *Player 6 | pre_state string 7 | } 8 | 9 | func NewPlayCommand(p *Player) *PlayCommand { 10 | return &PlayCommand{Player: p, pre_state: ""} 11 | } 12 | 13 | func (this *PlayCommand) Excute() string { 14 | this.pre_state = this.Player.GetState() 15 | this.Player.Playing() 16 | return this.Player.GetState() 17 | } 18 | 19 | func (this *PlayCommand) Undo() string { 20 | if this.pre_state == "pause" { 21 | this.Player.Pause() 22 | } else if this.pre_state == "playing" { 23 | this.Player.Playing() 24 | } else if this.pre_state == "stop" { 25 | this.Player.Stop() 26 | } 27 | 28 | return this.Player.GetState() 29 | } 30 | -------------------------------------------------------------------------------- /Command/Go/command/StopCommand.go: -------------------------------------------------------------------------------- 1 | package command 2 | 3 | type StopCommand struct { 4 | command 5 | *Player 6 | pre_state string 7 | } 8 | 9 | func NewStopCommand(p *Player) *StopCommand { 10 | return &StopCommand{Player: p, pre_state: ""} 11 | } 12 | 13 | func (this *StopCommand) Excute() string { 14 | this.pre_state = this.Player.GetState() 15 | this.Player.Stop() 16 | return this.Player.GetState() 17 | } 18 | 19 | func (this *StopCommand) Undo() string { 20 | if this.pre_state == "pause" { 21 | this.Player.Pause() 22 | } else if this.pre_state == "playing" { 23 | this.Player.Playing() 24 | } else if this.pre_state == "stop" { 25 | this.Player.Stop() 26 | } 27 | 28 | return this.Player.GetState() 29 | } 30 | -------------------------------------------------------------------------------- /Command/Go/command/PauseCommand.go: -------------------------------------------------------------------------------- 1 | package command 2 | 3 | type PauseCommand struct { 4 | command 5 | *Player 6 | pre_state string 7 | } 8 | 9 | func NewPauseCommand(p *Player) *PauseCommand { 10 | return &PauseCommand{Player: p, pre_state: ""} 11 | } 12 | 13 | func (this *PauseCommand) Excute() string { 14 | this.pre_state = this.Player.GetState() 15 | this.Player.Pause() 16 | return this.Player.GetState() 17 | } 18 | 19 | func (this *PauseCommand) Undo() string { 20 | if this.pre_state == "pause" { 21 | this.Player.Pause() 22 | } else if this.pre_state == "playing" { 23 | this.Player.Playing() 24 | } else if this.pre_state == "stop" { 25 | this.Player.Stop() 26 | } 27 | 28 | return this.Player.GetState() 29 | } 30 | -------------------------------------------------------------------------------- /Iterator/PHP/GoodsIterator.php: -------------------------------------------------------------------------------- 1 | goods_list = $goods_list; 9 | } 10 | 11 | public function current() { 12 | return $this->goods_list->getGoods($this->current_idx); 13 | } 14 | 15 | public function next() { 16 | $this->current_idx++; 17 | } 18 | 19 | public function key() { 20 | return $this->current_idx; 21 | } 22 | 23 | public function valid() { 24 | return null !== $this->goods_list->getGoods($this->current_idx); 25 | } 26 | 27 | public function rewind() { 28 | $this->current_idx = 0; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Flyweight/PHP/AuthorizationFlyweight.php: -------------------------------------------------------------------------------- 1 | security_entity, $this->permit) = $arr; 10 | } 11 | 12 | public function getSecurityEntity() { 13 | return $this->security_entity; 14 | } 15 | 16 | public function getPermit() { 17 | return $this->permit; 18 | } 19 | 20 | public function match($security_entity, $permit) { 21 | if ($this->security_entity == $security_entity && 22 | $this->permit == $permit) { 23 | return true; 24 | } 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Command/PHP/StopCommand.php: -------------------------------------------------------------------------------- 1 | player = $player; 7 | } 8 | 9 | public function excute() { 10 | $this->pre_state = $this->player->getState(); 11 | $this->player->stop(); 12 | echo $this->player->getState() . "\n"; 13 | } 14 | 15 | public function undo() { 16 | if ($this->pre_state == "pause") { 17 | $this->player->pause(); 18 | } else if ($this->pre_state == "playing") { 19 | $this->player->playing(); 20 | } else if ($this->pre_state == "stop" ) { 21 | $this->player->stop(); 22 | } 23 | 24 | echo $this->player->getState() . "\n"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Iterator/PHP/GoodsList.php: -------------------------------------------------------------------------------- 1 | goodses[$idx])) { 7 | return $this->goodses[$idx]; 8 | } 9 | 10 | return null; 11 | } 12 | 13 | public function addGoods($goods) { 14 | $this->goodses[] = $goods; 15 | return $this->count(); 16 | } 17 | 18 | public function removeGoods($goods) { 19 | foreach ($this->goodses as $key) { 20 | if ($this->goodses[$key]->getName() == $goods->getName()) { 21 | unset($this->goodses[$key]); 22 | } 23 | } 24 | 25 | return $this->count(); 26 | } 27 | 28 | public function count() { 29 | return count($this->goodses); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Iterator/Go/iterator/GoodsIterator.go: -------------------------------------------------------------------------------- 1 | package iterator 2 | 3 | type GoodsIterator struct { 4 | goods_list *GoodsList 5 | Current_idx int 6 | } 7 | 8 | func NewGoodsIterator(goods_list *GoodsList) *GoodsIterator { 9 | return &GoodsIterator{goods_list, 0} 10 | } 11 | 12 | func (this *GoodsIterator) Current() *Goods { 13 | return this.goods_list.GetGoods(this.Current_idx) 14 | } 15 | 16 | func (this *GoodsIterator) Next() { 17 | this.Current_idx++ 18 | } 19 | 20 | func (this *GoodsIterator) Key() int { 21 | return this.Current_idx 22 | } 23 | 24 | func (this *GoodsIterator) Valid() bool { 25 | if this.Current_idx >= this.goods_list.Count() { 26 | return false 27 | } 28 | 29 | return true 30 | } 31 | 32 | func (this *GoodsIterator) Rewind() { 33 | this.Current_idx = 0 34 | } 35 | -------------------------------------------------------------------------------- /Factory/FactoryMethod/PHP/test.php: -------------------------------------------------------------------------------- 1 | createPhone(); 16 | echo "Get phone " . $iphone->getName() . "\n"; 17 | 18 | $android = $androidFactory->createPhone(); 19 | echo "Get phone " . $android->getName() . "\n"; 20 | 21 | $other = $otherFactory->createPhone(); 22 | echo "Get phone " . $other->getName() . "\n"; 23 | ?> 24 | -------------------------------------------------------------------------------- /Flyweight/Go/flyweight/AuthorizationFactory.go: -------------------------------------------------------------------------------- 1 | package flyweight 2 | 3 | import "strings" 4 | 5 | type AuthorizationFactory struct { 6 | security_entity string 7 | permit string 8 | } 9 | 10 | func NewAuthorizationFactory(state string) *AuthorizationFactory { 11 | arr := strings.Split(state, ",") 12 | return &AuthorizationFactory{arr[0], arr[1]} 13 | } 14 | 15 | func (this *AuthorizationFactory) GetSecurityEntity() string { 16 | return this.security_entity 17 | } 18 | 19 | func (this *AuthorizationFactory) GetPermit() string { 20 | return this.permit 21 | } 22 | 23 | func (this *AuthorizationFactory) Match(security_entity string, permit string) bool { 24 | if this.security_entity == security_entity && this.permit == permit { 25 | return true 26 | } 27 | 28 | return false 29 | } 30 | -------------------------------------------------------------------------------- /Command/PHP/PauseCommand.php: -------------------------------------------------------------------------------- 1 | player = $player; 8 | } 9 | 10 | public function excute() { 11 | $this->pre_state = $this->player->getState(); 12 | $this->player->pause(); 13 | echo $this->player->getState() . "\n"; 14 | } 15 | 16 | public function undo() { 17 | if ($this->pre_state == "pause") { 18 | $this->player->pause(); 19 | } else if ($this->pre_state == "playing") { 20 | $this->player->playing(); 21 | } else if($this->pre_state == "stop") { 22 | $this->player->stop(); 23 | } 24 | 25 | echo $this->player->getState() . "\n"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Mediator/Go/mediator/Model.go: -------------------------------------------------------------------------------- 1 | package mediator 2 | 3 | type Model struct { 4 | *Colleague 5 | user_list []string 6 | } 7 | 8 | func NewModel(mediator Mediator) *Model { 9 | return &Model{Colleague: &Colleague{mediator}} 10 | } 11 | 12 | func (this *Model) AddUser(user string) { 13 | this.user_list = append(this.user_list, user) 14 | } 15 | 16 | func (this *Model) GetUserList() []string { 17 | return this.user_list 18 | } 19 | 20 | func (this *Model) DeleteUser(user string) { 21 | for idx, u := range this.user_list { 22 | if u == user { 23 | this.user_list = append(this.user_list[:idx], this.user_list[idx+1:]...) 24 | this.Colleague.GetMediator().ShowResult("删除" + user + "成功") 25 | return 26 | } 27 | } 28 | 29 | this.Colleague.GetMediator().ShowResult("删除" + user + "失败,该用户不存在") 30 | } 31 | -------------------------------------------------------------------------------- /Mediator/PHP/Model.php: -------------------------------------------------------------------------------- 1 | user_list[] = $user; 12 | } 13 | 14 | public function getUserList() { 15 | return $this->user_list; 16 | } 17 | 18 | public function deleteUser($user) { 19 | foreach ($this->user_list as $key => $user_name) { 20 | if ($user_name == $user) { 21 | unset($this->user_list[$key]); 22 | $this->getMeditor()->showResult("删除" . $user . "成功\n"); 23 | return; 24 | } 25 | } 26 | 27 | $this->getMeditor()->showResult("删除" . $user . "失败,该用户不存在\n"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Command/PHP/PlayCommand.php: -------------------------------------------------------------------------------- 1 | player = $player; 8 | $this->pre_state = ""; 9 | } 10 | 11 | public function excute() { 12 | $this->pre_state = $this->player->getState(); 13 | $this->player->playing(); 14 | echo $this->player->getState() . "\n"; 15 | } 16 | 17 | public function undo() { 18 | if ($this->pre_state == "pause") { 19 | $this->player->pause(); 20 | } else if ($this->pre_state == "playing") { 21 | $this->player->playing(); 22 | } else if ($this->pre_state == "stop") { 23 | $this->player->stop(); 24 | } 25 | 26 | echo $this->player->getState() . "\n"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Mediator/Go/mediator/View.go: -------------------------------------------------------------------------------- 1 | package mediator 2 | 3 | import "fmt" 4 | 5 | type View struct { 6 | *Colleague 7 | } 8 | 9 | func NewView(media Mediator) *View { 10 | return &View{&Colleague{media}} 11 | } 12 | 13 | func (this *View) MakeAddRequest(user string) { 14 | fmt.Println("发起增加用户" + user + "请求") 15 | this.Colleague.GetMediator().AddUser(user) 16 | } 17 | 18 | func (this *View) ShowUser() { 19 | fmt.Println("当前用户如下:\n--------") 20 | user_list := this.Colleague.GetMediator().GetUserList() 21 | for _, u := range user_list { 22 | fmt.Println(u) 23 | } 24 | fmt.Println("--------") 25 | } 26 | 27 | func (this *View) MakeDeleteRequest(user string) { 28 | fmt.Println("发起删除用户" + user + "请求") 29 | this.Colleague.GetMediator().DeleteUser(user) 30 | } 31 | 32 | func (this *View) ShowResult(result string) { 33 | fmt.Println(result) 34 | } 35 | -------------------------------------------------------------------------------- /Iterator/Go/iterator/GoodsList.go: -------------------------------------------------------------------------------- 1 | package iterator 2 | 3 | type GoodsList struct { 4 | goodses []*Goods 5 | } 6 | 7 | func (this *GoodsList) GetGoods(idx int) *Goods { 8 | if this.goodses[idx] != nil { 9 | return this.goodses[idx] 10 | } 11 | 12 | return nil 13 | } 14 | 15 | func (this *GoodsList) AddGoods(goods *Goods) int { 16 | this.goodses = append(this.goodses, goods) 17 | return this.Count() 18 | } 19 | 20 | func (this *GoodsList) RemoveGoods(goods *Goods) int { 21 | t_idx := -1 22 | for idx, g := range this.goodses { 23 | if g.GetName() == goods.GetName() { 24 | t_idx = idx 25 | break 26 | } 27 | } 28 | 29 | if t_idx != -1 { 30 | this.goodses = append(this.goodses[:t_idx], this.goodses[t_idx+1:]...) 31 | } 32 | 33 | return this.Count() 34 | } 35 | 36 | func (this *GoodsList) Count() int { 37 | return len(this.goodses) 38 | } 39 | -------------------------------------------------------------------------------- /Prototype/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./prototype" 4 | import "fmt" 5 | 6 | func main() { 7 | life_article := &prototype.LifeArticle{} 8 | tech_article := &prototype.TechArticle{} 9 | life_article.SetTitle("Life") 10 | tech_article.SetTitle("techology") 11 | author_hector := prototype.NewAuthor("hector") 12 | author_tom := prototype.NewAuthor("tom") 13 | life_article.SetAuthor(author_hector) 14 | tech_article.SetAuthor(author_tom) 15 | 16 | clone_life := life_article.Clone() 17 | clone_tech := tech_article.Clone() 18 | clone_life.SetTitle("Programmer life") 19 | 20 | fmt.Printf("%s\n", clone_life.GetTitle()) 21 | fmt.Printf("%s\n", life_article.GetTitle()) 22 | fmt.Printf("%s\n", clone_tech.GetTitle()) 23 | 24 | clone_life.GetAuthor().SetName("haha") 25 | fmt.Printf("%s\n", clone_life.GetAuthor().GetName()) 26 | fmt.Printf("%s\n", life_article.GetAuthor().GetName()) 27 | } 28 | -------------------------------------------------------------------------------- /Factory/AbstractFactory/PHP/test.php: -------------------------------------------------------------------------------- 1 | createOS("ios"); 16 | echo $iphone_os->create(); 17 | $iphone_special = $iPhoneFactory->createSpecial("siri"); 18 | echo $iphone_special->create(); 19 | 20 | $androidFactory = new AndroidFactory(); 21 | $android_os = $androidFactory->createOS("android"); 22 | echo $android_os->create(); 23 | $android_special = $iPhoneFactory->createSpecial("nfc"); 24 | echo $android_special->create(); 25 | ?> 26 | -------------------------------------------------------------------------------- /Composite/PHP/ParentNavigation.php: -------------------------------------------------------------------------------- 1 | name = $name; 8 | } 9 | 10 | public function add($navigation_component) { 11 | $this->childs[] = $navigation_component; 12 | } 13 | 14 | public function remove($navigation_component) { 15 | foreach ($childs as $key => $child) { 16 | if ($child->getName() == $navigation_component->getName()) { 17 | unset($childs[$key]); 18 | break; 19 | } 20 | } 21 | } 22 | 23 | public function getChild() { 24 | $result = ""; 25 | foreach ($this->childs as $child) { 26 | $result .= " " . $child->getName(); 27 | } 28 | return $result; 29 | } 30 | 31 | public function getName() { 32 | return $this->name; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Bridge/PHP/test.php: -------------------------------------------------------------------------------- 1 | sendMessage("hello", "tom"); 14 | 15 | $m = new UrgencyMessage($impl); 16 | $m->sendMessage("hello", "tom"); 17 | 18 | $m = new SpecialUrgencyMessage($impl); 19 | $m->sendMessage("hello", "tom"); 20 | 21 | $impl = new MessageMobile(); 22 | $m = new CommonMessage($impl); 23 | $m->sendMessage("hello", "tom"); 24 | 25 | $m = new UrgencyMessage($impl); 26 | $m->sendMessage("hello", "tom"); 27 | 28 | $m = new SpecialUrgencyMessage($impl); 29 | $m->sendMessage("hello", "tom"); 30 | -------------------------------------------------------------------------------- /Composite/Go/composite/ParentNavigation.go: -------------------------------------------------------------------------------- 1 | package composite 2 | 3 | type ParentNavigation struct { 4 | Childs []navigationcomponent 5 | *BaseNavigation 6 | } 7 | 8 | func NewParentNavigation(name string) *ParentNavigation { 9 | return &ParentNavigation{BaseNavigation: &BaseNavigation{Name: name}} 10 | } 11 | 12 | func (this *ParentNavigation) Add(navigationcomponent navigationcomponent) { 13 | this.Childs = append(this.Childs, navigationcomponent) 14 | } 15 | 16 | func (this *ParentNavigation) Remove(navigationcomponent navigationcomponent) { 17 | c_idx := -1 18 | for idx, c := range this.Childs { 19 | if c.GetName() == navigationcomponent.GetName() { 20 | c_idx = idx 21 | } 22 | } 23 | 24 | this.Childs = append(this.Childs[:c_idx], this.Childs[c_idx+1:]...) 25 | } 26 | 27 | func (this *ParentNavigation) GetChild() string { 28 | result := "" 29 | for _, c := range this.Childs { 30 | result += " " + c.GetName() 31 | } 32 | return result 33 | } 34 | -------------------------------------------------------------------------------- /Decorator/PHP/test.php: -------------------------------------------------------------------------------- 1 | getDescription() . "===price : " . $double_mocha->cost() . "$\n"; 25 | echo "description " . $espresso_soy->getDescription() . "===price : " . $espresso_soy->cost() . "$\n"; 26 | echo "description " . $espresso_soy_mocha->getDescription() . "===price : " . $espresso_soy_mocha->cost() . "$\n"; 27 | ?> 28 | -------------------------------------------------------------------------------- /Observer/PHP/concreteSubject.php: -------------------------------------------------------------------------------- 1 | _observers = array(); 9 | } 10 | 11 | public function registerObserver(Observer $observer) 12 | { 13 | array_push($this->_observers, $observer); 14 | } 15 | 16 | public function removeObserver(Observer $observer) 17 | { 18 | if ($index = array_search($observer, $this->_observers, true)) 19 | { 20 | unset($this->_observers[$index]); 21 | } 22 | } 23 | 24 | public function notify() 25 | { 26 | foreach ($this->_observers as $observer) 27 | { 28 | $observer->update($this->_value); 29 | } 30 | } 31 | 32 | public function setValue($value) 33 | { 34 | $this->_value = $value; 35 | $this->notify(); 36 | } 37 | 38 | public function getValue() 39 | { 40 | return $this->_value; 41 | } 42 | } 43 | ?> 44 | -------------------------------------------------------------------------------- /Memento/Go/memento/Workout.go: -------------------------------------------------------------------------------- 1 | package memento 2 | 3 | import "fmt" 4 | 5 | type Workout struct { 6 | temp_record string 7 | temp_time int 8 | } 9 | 10 | func NewWorkout() *Workout { 11 | return &Workout{"", 0} 12 | } 13 | 14 | func (this *Workout) Running() { 15 | this.temp_record = "running 5 km;" 16 | this.temp_time = 33 17 | } 18 | 19 | func (this *Workout) Bicycle() { 20 | this.temp_record += "ride bicycle 5 km;" 21 | this.temp_time += 20 22 | this.printResult() 23 | } 24 | 25 | func (this *Workout) AbdominalRipperX() { 26 | this.temp_record += "finish abdominal ripper x;" 27 | this.temp_time += 30 28 | this.printResult() 29 | } 30 | 31 | func (this *Workout) CreateMemento() *Memento { 32 | return &Memento{this.temp_record, this.temp_time} 33 | } 34 | 35 | func (this *Workout) SetMemento(memento *Memento) { 36 | this.temp_record = memento.GetTempRecord() 37 | this.temp_time = memento.GetTempTime() 38 | } 39 | 40 | func (this *Workout) printResult() { 41 | fmt.Printf("%scost %d mins\n", this.temp_record, this.temp_time) 42 | } 43 | -------------------------------------------------------------------------------- /State/Go/state/VoteManager.go: -------------------------------------------------------------------------------- 1 | package state 2 | 3 | type VoteManager struct { 4 | Votes map[string]string 5 | vote_count map[string]int 6 | state votestate 7 | } 8 | 9 | func NewVoteManager() *VoteManager { 10 | return &VoteManager{Votes: make(map[string]string), vote_count: make(map[string]int)} 11 | } 12 | 13 | func (this *VoteManager) Add(user_name string, item string) { 14 | this.Votes[user_name] = item 15 | } 16 | 17 | func (this *VoteManager) Vote(user_name string, item string) { 18 | if _, ok := this.vote_count[user_name];!ok { 19 | this.vote_count[user_name] = 0 20 | } 21 | 22 | this.vote_count[user_name]++ 23 | current_count := this.vote_count[user_name] 24 | if current_count == 1 { 25 | this.state = &NormalVoteState{} 26 | } else if current_count > 1 && current_count < 5 { 27 | this.state = &RepeatVoteState{} 28 | } else if current_count > 5 && current_count < 8 { 29 | this.state = &SpiteVoteState{} 30 | } else if current_count > 8 { 31 | this.state = &BlackVoteState{} 32 | } 33 | 34 | this.state.HandleVote(user_name, item, this) 35 | } 36 | -------------------------------------------------------------------------------- /State/PHP/VoteManager.php: -------------------------------------------------------------------------------- 1 | votes = array(); 9 | $this->vote_count = array(); 10 | } 11 | 12 | public function add($user, $item) { 13 | $this->vote[] = array("user" => $user, "item" => $item); 14 | } 15 | 16 | public function vote($user, $item) { 17 | if (!isset($this->vote_count[$user])) { 18 | $this->vote_count[$user] = 0; 19 | } 20 | $current_count = ++$this->vote_count[$user]; 21 | 22 | if ($current_count == 1) { 23 | $this->state = new NormalVoteState(); 24 | } elseif($current_count > 1 && $current_count < 5) { 25 | $this->state = new RepeatVoteState(); 26 | } elseif ($current_count >= 5 && $current_count < 8) { 27 | $this->state = new SpiteVoteState(); 28 | } elseif ($current_count > 8) { 29 | $this->state = new BlackVoteState(); 30 | } 31 | 32 | $this->state->handleVote($user, $item, $this); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Decorator/Go/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "./decorator" 5 | 6 | func main() { 7 | dark_roast := decorator.NewDarkRoast() 8 | espresso := decorator.NewEspresso() 9 | decaf := decorator.NewDecaf() 10 | house_blend := decorator.NewHouseBlend() 11 | 12 | mocha := decorator.NewMocha(dark_roast); 13 | double_mocha := decorator.NewMocha(mocha); 14 | 15 | espresso_soy := decorator.NewSoy(espresso) 16 | espresso_soy_mocha := decorator.NewMocha(espresso_soy) 17 | 18 | fmt.Printf("description\n%s === price: %.2f$\n\n", decaf.GetDescription(), decaf.Cost()); 19 | fmt.Printf("description\n%s === price: %.2f$\n\n", house_blend.GetDescription(), house_blend.Cost()); 20 | fmt.Printf("description\n%s === price: %.2f$\n\n", mocha.GetDescription(), mocha.Cost()); 21 | fmt.Printf("description\n%s === price: %.2f$\n\n", double_mocha.GetDescription(), double_mocha.Cost()); 22 | fmt.Printf("description\n%s === price: %.2f$\n\n", espresso_soy.GetDescription(), espresso_soy.Cost()); 23 | fmt.Printf("description\n%s === price: %.2f$\n\n", espresso_soy_mocha.GetDescription(), espresso_soy_mocha.Cost()); 24 | } 25 | -------------------------------------------------------------------------------- /Memento/PHP/Workout.php: -------------------------------------------------------------------------------- 1 | temp_record = ""; 10 | $this->temp_time = 0; 11 | } 12 | 13 | public function running() { 14 | $this->temp_record = "running 5 km;"; 15 | $this->temp_time = 33; 16 | } 17 | 18 | public function bicycle() { 19 | $this->temp_record .= "ride bicycle 5 km;"; 20 | $this->temp_time += 20; 21 | // echo $this->temp_record . " cost " . $this->temp_time . "mins\n"; 22 | } 23 | 24 | public function abdominal_ripper_x() { 25 | $this->temp_record .= "finish abdominal ripper x;"; 26 | $this->temp_time += 30; 27 | echo $this->temp_record . " cost " . $this->temp_time . "mins\n"; 28 | } 29 | 30 | public function createMemento() { 31 | return new Memento($this->temp_record, $this->temp_time); 32 | } 33 | 34 | public function setMemento($memento) { 35 | $this->temp_record = $memento->getTempRecord(); 36 | $this->temp_time = $memento->getTempTime(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Interpreter/PHP/Calculator.php: -------------------------------------------------------------------------------- 1 | "PlusExpression", "-" => "MinusExpression", 7 | "*" => "MulExpression", "/" => "DivExpression", "%" => "ModExpression"); 8 | 9 | public function init($statement) { 10 | $expression_stack = array(); 11 | $left = null; 12 | $right = null; 13 | 14 | $statement_arr = explode(" ", $statement); 15 | for ($i = 0; $i < count($statement_arr); ++$i) { 16 | echo "run"; 17 | $elem = $statement_arr[$i]; 18 | if (in_array($elem, $this->symbol_arr)) { 19 | $left = array_pop($expression_stack); 20 | $right = new ValueExpression($statement_arr[++$i]); 21 | print_r($left); 22 | print_r($right); 23 | array_push($expression_stack, new $this->symbol_map[$elem]($left, $right)); 24 | } else { 25 | array_push($expression_stack, new ValueExpression($elem)); 26 | } 27 | } 28 | $this->expression = array_pop($expression_stack); 29 | } 30 | 31 | public function compute() { 32 | return $this->expression->calculate(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Flyweight/PHP/SecurityMgr.php: -------------------------------------------------------------------------------- 1 | map = array(); 11 | } 12 | 13 | public static function getInstance() { 14 | if (self::$instance == null) { 15 | self::$instance = new self(); 16 | } 17 | 18 | return self::$instance; 19 | } 20 | 21 | public function login($user) { 22 | $col = $this->queryUser($user); 23 | $this->map[$user] = $col; 24 | } 25 | 26 | public function hasPermit($user, $security_entity, $permit) { 27 | $col = $this->map[$user]; 28 | if ($col == null || count($col) == 0) { 29 | echo $user . "没有登录或是没有被分配任何权限"; 30 | return false; 31 | } 32 | 33 | foreach ($col as $fm) { 34 | if ($fm->match($security_entity, $permit)) { 35 | return true; 36 | } 37 | } 38 | 39 | return false; 40 | } 41 | 42 | private function queryUser($user) { 43 | $col = array(); 44 | foreach (self::$user_data as $data) { 45 | $str = explode(",", $data); 46 | if ($str[0] == $user) { 47 | $fm = FlyweightFactory::getInstance()->getFlyweight($str[1] . ',' . $str[2]); 48 | $col[] = $fm; 49 | } 50 | } 51 | return $col; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Flyweight/Go/flyweight/SecurityMgr.go: -------------------------------------------------------------------------------- 1 | package flyweight 2 | 3 | import "strings" 4 | import "fmt" 5 | 6 | type SecurityMgr struct { 7 | map_user map[string][]*AuthorizationFactory 8 | } 9 | 10 | var s_instance *SecurityMgr 11 | 12 | var user_data = [2]string{"hhq,money,look", "tom,money,get"} 13 | 14 | func GetSInstance() *SecurityMgr { 15 | if instance == nil { 16 | s_instance = &SecurityMgr{} 17 | } 18 | 19 | return s_instance 20 | } 21 | 22 | func (this *SecurityMgr) Login(user string) { 23 | col := this.queryUser(user) 24 | if this.map_user == nil { 25 | this.map_user = make(map[string][]*AuthorizationFactory) 26 | } 27 | this.map_user[user] = col 28 | } 29 | 30 | func (this *SecurityMgr) HasPermit(user string, security_entity string, permit string) bool { 31 | col := this.map_user[user] 32 | if col == nil || len(col) == 0 { 33 | fmt.Println(user + "没有登录或是没有被分配到任何权限") 34 | return false 35 | } 36 | 37 | for _, fm := range col { 38 | if fm.Match(security_entity, permit) { 39 | return true 40 | } 41 | } 42 | 43 | return false 44 | } 45 | 46 | func (this *SecurityMgr) queryUser(user string) []*AuthorizationFactory{ 47 | var col []*AuthorizationFactory 48 | for _, data := range user_data { 49 | str := strings.Split(data, ",") 50 | if str[0] == user { 51 | fm := GetInstance().GetFlyweight(str[1] + "," + str[2]) 52 | col = append(col, fm) 53 | } 54 | } 55 | 56 | return col 57 | } 58 | -------------------------------------------------------------------------------- /Interpreter/Go/interpreter/Calculator.go: -------------------------------------------------------------------------------- 1 | package interpreter 2 | 3 | import "strings" 4 | import "strconv" 5 | 6 | type Stack struct { 7 | top *Element 8 | size int 9 | } 10 | 11 | type Element struct { 12 | value Expression // All types satisfy the empty interface, so we can store anything here. 13 | next *Element 14 | } 15 | 16 | // Return the stack's length 17 | func (s *Stack) Len() int { 18 | return s.size 19 | } 20 | 21 | // Push a new element onto the stack 22 | func (s *Stack) Push(value Expression) { 23 | s.top = &Element{value, s.top} 24 | s.size++ 25 | } 26 | 27 | // Remove the top element from the stack and return it's value 28 | // If the stack is empty, return nil 29 | func (s *Stack) Pop() (value Expression) { 30 | if s.size > 0 { 31 | value, s.top = s.top.value, s.top.next 32 | s.size-- 33 | return 34 | } 35 | return nil 36 | } 37 | 38 | type Calculator struct { 39 | statement string 40 | expression Expression 41 | Symbol_arr [5]string 42 | } 43 | 44 | func inArray(arr [5]string, elem string) bool { 45 | for _, data := range arr { 46 | if elem == data { 47 | return true 48 | } 49 | } 50 | 51 | return false 52 | } 53 | 54 | func (this *Calculator) Init(statement string) { 55 | expression_stack := new(Stack) 56 | var Left Expression 57 | var Right Expression 58 | 59 | statement_arr := strings.Split(statement, " ") 60 | for idx := 0; idx < len(statement_arr); idx++ { 61 | elem := statement_arr[idx] 62 | if inArray(this.Symbol_arr, elem) { 63 | Left = expression_stack.Pop() 64 | value, _ := strconv.Atoi(statement_arr[idx+1]) 65 | idx = idx + 1 66 | Right = NewValueExpression(value) 67 | if elem == "+" { 68 | expression_stack.Push(NewPlusExpression(Left, Right)) 69 | } else if elem == "-" { 70 | expression_stack.Push(NewMinusExpression(Left, Right)) 71 | } else if elem == "*" { 72 | expression_stack.Push(NewMulExpression(Left, Right)) 73 | } else if elem == "/" { 74 | expression_stack.Push(NewDivExpression(Left, Right)) 75 | } else { 76 | expression_stack.Push(NewModExpression(Left, Right)) 77 | } 78 | } else { 79 | value2, _ := strconv.Atoi(elem) 80 | expression_stack.Push(NewValueExpression(value2)) 81 | } 82 | } 83 | this.expression = expression_stack.Pop() 84 | } 85 | 86 | func (this *Calculator) Compute() int { 87 | return this.expression.Calculate() 88 | } 89 | --------------------------------------------------------------------------------