共计 1966 个字符,预计需要花费 5 分钟才能阅读完成。
概念
简单来讲就是提供一种创建创建对象的方式。工厂设计模式主要有三种类型:简单工厂模式、工厂方法模式和抽象工厂模式。本文将针对这三种设计模式一一进行介绍。
简单工厂
简单工厂模式是最常用的一种工厂设计模式,它将对象的创建过程封装在一个工厂类中,客户端通过向工厂类传递参数,来获取所需的对象。
简单工厂模式的核心在于工厂类的设计,它通过代码的封装,隔离了客户端和具体的实现类,从而降低了耦合性,并提高了代码的可维护性。
下面是一个简单工厂的示例代码:
type Animal interface {Sing()
}
type Dog struct {
}
func (d *Dog) Sing() {fmt.Println(" 旺旺 ")
}
type Pig struct {Animal}
func (p *Pig) Sing() {fmt.Println(" 呼噜”")
}
func CreateAnimal(category string) Animal {
switch category {
case "dog":
return &Dog{}
case "pig":
return &Pig{}
default:
return nil
}
}
func main() {dog := CreateAnimal("Dog")
dog.Sing()
pig := CreateAnimal("Pig")
pig.Sing()}
工厂方法
在工厂方法模式中,抽象工厂类提供一个接口用于创建对象,而其具体的实现类将负责具体的对象创建。工厂方法模式将对象创建的责任委托给具体的子类,从而支持灵活的对象创建。
下面是一个工厂方法的示例代码:
type Animal interface {Sing()
}
type Dog struct {
}
func (d *Dog) Sing() {fmt.Println(" 旺旺 ")
}
type Pig struct {Animal}
func (p *Pig) Sing() {fmt.Println(" 呼噜”")
}
type AnimalFactory interface {CreateAnimal() Animal
}
type DogFactory struct {
}
func (d *DogFactory) CreateAnimal() Animal {return &Dog{}
}
type PigFactory struct {
}
func (p *PigFactory) CreateAnimal() Animal {return &Pig{}
}
func main() {dogFactory := &DogFactory{}
dog := dogFactory.CreateAnimal()
dog.Sing()
pigFactory := &PigFactory{}
pig := pigFactory.CreateAnimal()
pig.Sing()}
抽象工厂
抽象工厂模式是一种将多个工厂组合在一起的设计模式。在抽象工厂模式中,抽象工厂类提供一个接口,用于创建各个产品族的对象。而各个具体的工厂类将实现这个接口,并负责具体的产品对象创建。抽象工厂模式的优点在于可以将对象创建的过程封装起来,从而提高了代码的可维护性。
下面是一个抽象工厂模式的示例代码:
type Animal interface {Sing()
}
type Dog struct {
}
func (d *Dog) Sing() {fmt.Println(" 旺旺 ")
}
type Pig struct {Animal}
func (p *Pig) Sing() {fmt.Println(" 呼噜”")
}
type AnimalFactory interface {CreateBig() Animal
CreateBSmall() Animal}
type DogFactory struct {
}
func (d *DogFactory) CreateBig() Animal {return &Dog{}
}
func (d *DogFactory) CreateSmall() Animal {return &Dog{}
}
type PigFactory struct {
}
func (p *PigFactory) CreateBig() Animal {return &Pig{}
}
func (p *PigFactory) CreateSmall() Animal {return &Pig{}
}
func main() {dogFactory := &DogFactory{}
smallDog := dogFactory.CreateSmall()
bigDog := dogFactory.CreateBig()
smallDog.Sing()
bigDog.Sing()
pigFactory := &PigFactory{}
bigPig := pigFactory.CreateBig()
smallPig := pigFactory.CreateSmall()
bigPig.Sing()
smallPig.Sing()}
正文完
发表至: 设计模式
2023-04-05