pattern_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // 23pattern_test
  2. package pattern
  3. import "testing"
  4. func TestCreationalPatterns(t *testing.T) {
  5. // Singleton
  6. s1 := GetInstance()
  7. s2 := GetInstance()
  8. if s1 != s2 {
  9. t.Error("Singleton instances should be the same")
  10. }
  11. // Factory Method
  12. dog := CreateAnimal("dog")
  13. if dog.Speak() != "Woof!" {
  14. t.Error("Dog should say Woof!")
  15. }
  16. // Builder
  17. house := NewHouseBuilder().
  18. SetWindows(4).
  19. SetDoors(2).
  20. SetRoof("slate").
  21. Build()
  22. if house.windows != 4 {
  23. t.Error("House should have 4 windows")
  24. }
  25. }
  26. func TestStructuralPatterns(t *testing.T) {
  27. // Adapter
  28. printer := &PrinterAdapter{&MyLegacyPrinter{}}
  29. result := printer.PrintModern("test")
  30. if result != "Legacy: test" {
  31. t.Error("Adapter pattern failed")
  32. }
  33. // Decorator
  34. coffee := &SimpleCoffee{}
  35. coffeeWithMilk := &MilkDecorator{coffee: coffee}
  36. if coffeeWithMilk.Cost() != 7 {
  37. t.Error("Coffee with milk should cost 7")
  38. }
  39. }
  40. func TestBehavioralPatterns(t *testing.T) {
  41. // Strategy
  42. strategyA := &ConcreteStrategyA{}
  43. if strategyA.Execute() != "Strategy A" {
  44. t.Error("Strategy A failed")
  45. }
  46. // State
  47. context := &Context{state: &ConcreteStateA{}}
  48. if context.state.Handle() != "State A" {
  49. t.Error("State pattern failed")
  50. }
  51. }