728x90
반응형
Factory Pattern
운송업체별로 물리 프린터기 출력용지나 출력물 등 달라지는데 여기서는 물리 프린터기에서 출력을 위한 데이터를
팩토리 패턴으로 구현 하였다.
- PrineterMethod Interface 구현
- EMSPrinter, SFPrinter struct 구현 → GetOuput() 구현
- Create() 를 통해서 new() 로 사용할 Prineter를 Create and Return
- Return Struct의 GetOuput() 메소드를 통해 결과값 Return
factory.go
package factory
import (
"errors"
"fmt"
)
const (
EMS_CODE = "EMS"
SF_CODE = "SF"
)
type PrinterMethod interface {
GetOutput(code string) string
}
type EMSPrinter struct{}
type SFPrinter struct{}
func (p *EMSPrinter) GetOutput(packageCode string) string {
return fmt.Sprintf("<html><body><img src=\"http://host.com/%s.png\"></body></html>", packageCode)
}
func (p *SFPrinter) GetOutput(packageCode string) string {
return fmt.Sprintf("^BZ^X,Y,100,100,%s^BI^BZ", packageCode)
}
func CreatePrinterMethod(transferCompanyCode string) (PrinterMethod, error) {
switch transferCompanyCode {
case EMS_CODE:
return new(EMSPrinter), nil
case SF_CODE:
return new(SFPrinter), nil
default:
return nil, errors.New(fmt.Sprintf("%s is not implemented", transferCompanyCode))
}
}
factory_test.go
package factory_test
import (
"testing"
"github.com/go-playground/assert/v2"
"github.com/sanggi-wjg/go_demos/sample/pattern/factory"
)
func TestCreate(t *testing.T) {
// given
transferCompanyCode1 := factory.EMS_CODE
transferCompanyCode2 := factory.SF_CODE
transferCompanyCode3 := "What"
// when
method1, err1 := factory.CreatePrinterMethod(transferCompanyCode1)
method2, err2 := factory.CreatePrinterMethod(transferCompanyCode2)
method3, err3 := factory.CreatePrinterMethod(transferCompanyCode3)
// then
assert.Equal(t, method1, factory.EMSPrinter{})
assert.Equal(t, err1, nil)
assert.Equal(t, method2, factory.SFPrinter{})
assert.Equal(t, err2, nil)
assert.Equal(t, method3, nil)
assert.NotEqual(t, err3, nil)
}
func TestCreateEMS(t *testing.T) {
// given
packageCode := "123"
transferCompanyCode := factory.EMS_CODE
// when
printerMethod, err := factory.CreatePrinterMethod(transferCompanyCode)
output := printerMethod.GetOutput(packageCode)
// then
assert.Equal(t, err, nil)
assert.Equal(t, output, "<html><body><img src=\"http://host.com/123.png\"></body></html>")
}
func TestCreateSF(t *testing.T) {
// given
packageCode := "123"
transferCompanyCode := factory.SF_CODE
// when
printerMethod, err := factory.CreatePrinterMethod(transferCompanyCode)
output := printerMethod.GetOutput(packageCode)
// then
assert.Equal(t, err, nil)
assert.Equal(t, output, "^BZ^X,Y,100,100,123^BI^BZ")
}
728x90
반응형
'Go' 카테고리의 다른 글
[Go] Time (0) | 2022.08.02 |
---|---|
[Go] Channel 이용한 Queue (0) | 2022.07.24 |
[Go] Int, String, Struct 정렬 (0) | 2022.07.23 |
[Go] Linked List 구현 (0) | 2022.07.23 |
[Go] Panic recover 하기 (0) | 2022.07.23 |