高端品牌網(wǎng)站建設哪家好愛站
使用Golang實現(xiàn)開發(fā)中常用的【實例設計模式】
設計模式是解決常見問題的模板,可以幫助我們提升思維能力,編寫更高效、可維護性更強的代碼。
單例模式:
描述:確保一個類只有一個實例,并提供一個全局訪問點。
優(yōu)點:節(jié)省資源,避免重復創(chuàng)建對象。
缺點:單例對象通常是全局可訪問的,容易引起耦合。
package singletonimport ("sync"
)type Singleton struct {value string
}var instance *Singleton
var once sync.Oncefunc GetInstance() *Singleton {once.Do(func() {instance = &Singleton{}})return instance
}func (s *Singleton) SetValue(value string) {s.value = value
}func (s *Singleton) GetValue() string {return s.value
}
工廠模式:
描述:提供一個創(chuàng)建對象的接口,但由子類決定實例化哪一個類。
優(yōu)點:將對象的創(chuàng)建和使用分離,提高代碼的靈活性。
缺點:增加了代碼的復雜性。
package factorytype Product interface {Use()
}type ConcreteProductA struct{}func (p *ConcreteProductA) Use() {println("Using ConcreteProductA")
}type ConcreteProductB struct{}func (p *ConcreteProductB) Use() {println("Using ConcreteProductB")
}type Factory interface {CreateProduct() Product
}type ConcreteFactoryA struct{}func (f *ConcreteFactoryA) CreateProduct() Product {return &ConcreteProductA{}
}type ConcreteFactoryB struct{}func (f *ConcreteFactoryB) CreateProduct() Product {return &ConcreteProductB{}
}
觀察者模式:
描述:定義了對象之間的一對多依賴關系,當一個對象的狀態(tài)改變時,所有依賴于它的對象都會得到通知。
優(yōu)點:實現(xiàn)了對象之間的松耦合。
缺點:如果觀察者數(shù)量過多,通知過程可能會變得復雜。
package observertype Subject interface {RegisterObserver(observer Observer)RemoveObserver(observer Observer)NotifyObservers()
}type Observer interface {Update(data string)
}type ConcreteSubject struct {observers []Observerstate string
}func (s *ConcreteSubject) RegisterObserver(observer Observer) {s.observers = append(s.observers, observer)
}func (s *ConcreteSubject) RemoveObserver(observer Observer) {for i, obs := range s.observers {if obs == observer {s.observers = append(s.observers[:i], s.observers[i+1:]...)break}}
}func (s *ConcreteSubject) NotifyObservers() {for _, observer := range s.observers {observer.Update(s.state)}
}func (s *ConcreteSubject) SetState(state string) {s.state = states.NotifyObservers()
}type ConcreteObserver struct {name string
}func (o *ConcreteObserver) Update(data string) {println(o.name, "received:", data)
}
策略模式:
描述:定義一系列算法,把它們一個個封裝起來,并且使它們可以互相替換。
優(yōu)點:算法的變化獨立于使用算法的客戶。
缺點:增加了代碼的復雜性。
package strategytype Strategy interface {Execute(data string) string
}type Context struct {strategy Strategy
}func (c *Context) SetStrategy(strategy Strategy) {c.strategy = strategy
}func (c *Context) ExecuteStrategy(data string) string {return c.strategy.Execute(data)
}type ConcreteStrategyA struct{}func (s *ConcreteStrategyA) Execute(data string) string {return "ConcreteStrategyA executed with " + data
}type ConcreteStrategyB struct{}func (s *ConcreteStrategyB) Execute(data string) string {return "ConcreteStrategyB executed with " + data
}
裝飾者模式:
描述:動態(tài)地給一個對象添加一些額外的職責,而不必修改對象結(jié)構(gòu)。
優(yōu)點:增加了代碼的靈活性和可擴展性。
缺點:增加了代碼的復雜性。
package decoratortype Component interface {Operation() string
}type ConcreteComponent struct{}func (c *ConcreteComponent) Operation() string {return "ConcreteComponent operation"
}type Decorator struct {component Component
}func NewDecorator(component Component) *Decorator {return &Decorator{component: component}
}func (d *Decorator) Operation() string {return d.component.Operation()
}type ConcreteDecoratorA struct {Decorator
}func (d *ConcreteDecoratorA) Operation() string {return "ConcreteDecoratorA added to " + d.Decorator.Operation()
}type ConcreteDecoratorB struct {Decorator
}func (d *ConcreteDecoratorB) Operation() string {return "ConcreteDecoratorB added to " + d.Decorator.Operation()
}
代理模式:
描述:為其他對象提供一種代理以控制對這個對象的訪問。
優(yōu)點:增加了安全性和靈活性。
缺點:增加了代碼的復雜性。
package proxytype Subject interface {Request() string
}type RealSubject struct{}func (r *RealSubject) Request() string {return "RealSubject handling request"
}type Proxy struct {realSubject *RealSubject
}func NewProxy() *Proxy {return &Proxy{realSubject: &RealSubject{},}
}func (p *Proxy) Request() string {// Pre-processingprintln("Proxy: Checking access prior to firing a real request.")// Delegate to the real subjectresult := p.realSubject.Request()// Post-processingprintln("Proxy: Logging the time of request.")return result
}
分別調(diào)用不同模式的對象實例:
package mainimport ("fmt""singleton""factory""observer""strategy""decorator""proxy"
)func main() {// 單例模式singleton.GetInstance().SetValue("Hello, Singleton!")fmt.Println(singleton.GetInstance().GetValue())// 工廠模式factoryA := &factory.ConcreteFactoryA{}productA := factoryA.CreateProduct()productA.Use()factoryB := &factory.ConcreteFactoryB{}productB := factoryB.CreateProduct()productB.Use()// 觀察者模式subject := &observer.ConcreteSubject{}observerA := &observer.ConcreteObserver{name: "ObserverA"}observerB := &observer.ConcreteObserver{name: "ObserverB"}subject.RegisterObserver(observerA)subject.RegisterObserver(observerB)subject.SetState("New State")// 策略模式context := &strategy.Context{}strategyA := &strategy.ConcreteStrategyA{}strategyB := &strategy.ConcreteStrategyB{}context.SetStrategy(strategyA)fmt.Println(context.ExecuteStrategy("Data"))context.SetStrategy(strategyB)fmt.Println(context.ExecuteStrategy("Data"))// 裝飾者模式component := &decorator.ConcreteComponent{}decoratorA := &decorator.ConcreteDecoratorA{Decorator: *decorator.NewDecorator(component)}decoratorB := &decorator.ConcreteDecoratorB{Decorator: *decorator.NewDecorator(decoratorA)}fmt.Println(decoratorB.Operation())// 代理模式proxy := proxy.NewProxy()fmt.Println(proxy.Request())
}