53

[go设计模式]简单工厂模式

 4 years ago
source link: https://www.tuicool.com/articles/QJ32Uvy
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

优点

工厂类是整个模式的关键.包含了必要的逻辑判断,根据外界给定的信息,决定究竟应该创建哪个具体类的对象.通过使用工厂类,外界可以从直接创建具体产品对象的尴尬局面摆脱出来,仅仅需要负责“消费”对象就可以了。而不必管这些对象究竟如何创建及如何组织的.明确了各自的职责和权利,有利于整个软件体系结构的优化。

缺点

由于工厂类集中了所有实例的创建逻辑,违反了高内聚责任分配原则,将全部创建逻辑集中到了一个工厂类中;它所能创建的类只能是事先考虑到的,如果需要添加新的类,则就需要改变工厂类了。

当系统中的具体产品类不断增多时候,可能会出现要求工厂类根据不同条件创建不同实例的需求.这种对条件的判断和对具体产品类型的判断交错在一起,很难避免模块功能的蔓延,对系统的维护和扩展非常不利;

这些缺点在工厂方法模式中得到了一定的克服。

个人网易云课堂: https://m.study.163.com/provider/480000001930416/index.htm?share=2&shareId=480000001930416

package main
 
import (
	"fmt"
)
 
type Operation interface {
	Exe(int, int) int
}
 
type OperationAdd struct{}
type OperationSub struct{}
type OperationMul struct{}
type OperationDiv struct{}
 
func (this *OperationAdd) Exe(a int, b int) int {
	return a + b
}
 
func (this *OperationSub) Exe(a int, b int) int {
	return a - b
}
 
func (this *OperationMul) Exe(a int, b int) int {
	return a * b
}
 
func (this *OperationDiv) Exe(a int, b int) int {
	return a / b
}
 
func OperationFactory(oper string) Operation {
	switch oper {
	case "+":
		return &OperationAdd{}
	case "-":
		return &OperationSub{}
	case "*":
		return &OperationMul{}
	case "/":
		return &OperationDiv{}
	}
 
	return nil
}
 
func main() {
	fmt.Println(
		OperationFactory("+").Exe(10, 5),
		OperationFactory("-").Exe(10, 5),
		OperationFactory("*").Exe(10, 5),
		OperationFactory("/").Exe(10, 5))
}

输出结果:

15

5

50

2


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK