Abstract Factory/(Kit)
1. Intention
Provide an interface for creating a series of related or interdependent objects without specifying their specific classes.
2. Applicability
AbstractFactory mode can be used in the following situations:
- A system should be independent of the creation, combination and presentation of its products.
- When a system is to be configured by one of multiple product series.
- When you want to emphasize the design of a series of related product objects for joint use.
- When you provide a product class library, but only want to show their interface instead of implementation.
3. Structure
4. Code
package abstract
import (
"fmt"
"testing"
)
// 抽象工厂模式
type Girl interface {
weight()
}
// 中国胖女孩
type ChinaFatGirl struct {
}
func (ChinaFatGirl) weight() {
fmt.Println("中国胖女孩体重: 80kg")
}
// 瘦女孩
type ChinaThinGirl struct {
}
func (ChinaThinGirl) weight() {
fmt.Println("中国瘦女孩体重: 50kg")
}
type Factory interface {
CreateGirl(like string) Girl
}
// 中国工厂
type ChineseGirlFactory struct {
}
func (ChineseGirlFactory) CreateGirl(like string) Girl {
if like == "fat" {
return &ChinaFatGirl{
}
} else if like == "thin" {
return &ChinaThinGirl{
}
}
return nil
}
// 美国工厂
type AmericanGirlFactory struct {
}
func (AmericanGirlFactory) CreateGirl(like string) Girl {
if like == "fat" {
return &AmericanFatGirl{
}
} else if like == "thin" {
return &AmericanThainGirl{
}
}
return nil
}
// 美国胖女孩
type AmericanFatGirl struct {
}
func (AmericanFatGirl) weight() {
fmt.Println("American weight: 80kg")
}
// 美国瘦女孩
type AmericanThainGirl struct {
}
func (AmericanThainGirl) weight() {
fmt.Println("American weight: 50kg")
}
// 工厂提供者
type GirlFactoryStore struct {
factory Factory
}
func (store *GirlFactoryStore) createGirl(like string) Girl {
return store.factory.CreateGirl(like)
}
func TestAbstractFactory(t *testing.T) {
store := new(GirlFactoryStore)
// 提供美国工厂
store.factory = new(AmericanGirlFactory)
americanFatGirl := store.createGirl("fat")
americanFatGirl.weight()
// 提供中国工厂
store.factory = new(ChineseGirlFactory)
chineseFatGirl := store.createGirl("thin")
chineseFatGirl.weight()
}