抽象工厂模式(Abstract Factory)

抽象工厂模式(Abstract Factory)/(Kit)

1.意图

提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

2.适用性

在以下情况可以使用AbstractFactory模式:

  • 一个系统要独立于他的产品的创建、组合和表示时。
  • 一个系统要由多个产品系列中的一个来配置时。
  • 当你要强调一系列相关的产品对象的设计以便进行联合使用时。
  • 当你提供一个产品类库,而只想显示他们的接口而不是实现时。

3.结构

在这里插入图片描述

4.代码

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()
}

猜你喜欢

转载自blog.csdn.net/dawnto/article/details/112973355