内容简介:目的:在工厂类中选择接口的实现类来实例化,功能模块中不需要关心具体逻辑。使用条件:已经明确不同条件下创建相应实例。优点:调用者只需要创建一个对象并调用;扩展功能时也只需要扩展工厂类;屏蔽接口的具体实现,调用者只需要关心接口的调用。
目的:在工厂类中选择接口的实现类来实例化,功能模块中不需要关心具体逻辑。
使用条件:已经明确不同条件下创建相应实例。
优点:调用者只需要创建一个对象并调用;扩展功能时也只需要扩展工厂类;屏蔽接口的具体实现,调用者只需要关心接口的调用。
注意: 工厂模式与策略模式 差别在于此处是选择对接实体,而对接的接口功能是一致的。比如吃包子,工厂模式是选择哪家店吃包子。而策略模式是选择一家店之后,在那家店选择吃什么。
golang代码:
package factorypattern
import "fmt"
/*定义接口*/
type Animal interface {
Cry()
}
/*接口实现类1*/
type Dog struct {
}
/*接口实现类2*/
type Cat struct {
}
/*工厂类*/
type AnimalFactory struct {
}
/*实现类2实现接口的方法*/
func (Cat) Cry() {
fmt.Println("汪汪汪")
}
/*实现类1实现接口的方法*/
func (Dog) Cry() {
fmt.Println("喵喵喵")
}
/*工厂类方法实现*/
func (AnimalFactory) getAnimalObj(animalType string) (Animal){
var animal Animal
switch animalType {
case "cat":
animal = new(Cat)
break
case "dog":
animal = new(Dog)
break
default:
panic("no this kind animal")
}
return animal
}
/*测试*/
func Excute(){
new(AnimalFactory).getAnimalObj("cat").Cry()
new(AnimalFactory).getAnimalObj("dog").Cry()
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 设计模式-简单工厂、工厂方法模式、抽象工厂模式
- 简单工厂模式、工厂模式、抽象工厂模式的解析-iOS
- Java 设计模式之工厂方法模式与抽象工厂模式
- 设计模式-创建型模式-工厂模式(工厂三兄弟) TypeScript
- 设计模式之工厂模式(为什么很多人觉得工厂模式没有用)
- 设计模式 —— 工厂模式
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Algorithmic Beauty of Plants
Przemyslaw Prusinkiewicz、Aristid Lindenmayer / Springer / 1996-4-18 / USD 99.00
Now available in an affordable softcover edition, this classic in Springer's acclaimed Virtual Laboratory series is the first comprehensive account of the computer simulation of plant development. 150......一起来看看 《The Algorithmic Beauty of Plants》 这本书的介绍吧!