12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- // 23pattern_test
- package pattern
- import "testing"
- func TestCreationalPatterns(t *testing.T) {
- // Singleton
- s1 := GetInstance()
- s2 := GetInstance()
- if s1 != s2 {
- t.Error("Singleton instances should be the same")
- }
- // Factory Method
- dog := CreateAnimal("dog")
- if dog.Speak() != "Woof!" {
- t.Error("Dog should say Woof!")
- }
- // Builder
- house := NewHouseBuilder().
- SetWindows(4).
- SetDoors(2).
- SetRoof("slate").
- Build()
- if house.windows != 4 {
- t.Error("House should have 4 windows")
- }
- }
- func TestStructuralPatterns(t *testing.T) {
- // Adapter
- printer := &PrinterAdapter{&MyLegacyPrinter{}}
- result := printer.PrintModern("test")
- if result != "Legacy: test" {
- t.Error("Adapter pattern failed")
- }
- // Decorator
- coffee := &SimpleCoffee{}
- coffeeWithMilk := &MilkDecorator{coffee: coffee}
- if coffeeWithMilk.Cost() != 7 {
- t.Error("Coffee with milk should cost 7")
- }
- }
- func TestBehavioralPatterns(t *testing.T) {
- // Strategy
- strategyA := &ConcreteStrategyA{}
- if strategyA.Execute() != "Strategy A" {
- t.Error("Strategy A failed")
- }
- // State
- context := &Context{state: &ConcreteStateA{}}
- if context.state.Handle() != "State A" {
- t.Error("State pattern failed")
- }
- }
|