getReceiver
简单工厂模式.jpg代码:
package simplefactory
// Sender 发送
type Sender interface {
sender() bool
}
type MailSender struct {
}
func (ms *MailSender) sender() bool {
return false
}
type SmsSender struct {
}
func (ms *SmsSender) sender() bool {
return true
}
// SendFactory 发送工厂
type SendFactory struct {
}
func sender(senderType string) bool {
switch senderType {
case "mail":
return new(MailSender).sender()
case "sms":
return new(SmsSender).sender()
}
return false
}
缺点:不符合开闭原则
工厂模式
工厂模式.jpg代码:
package simplefactory
// Sender 发送
type Sender interface {
sender() bool
}
type MailSender struct {
}
func (ms *MailSender) sender() bool {
return false
}
type SmsSender struct {
}
func (ms *SmsSender) sender() bool {
return true
}
package factory
type factory interface {
getSender() bool
}
type mailfactory struct {
}
func (mf *mailfactory) getSender() bool {
return new(MailSender).sender()
}
type SmsSender struct {
}
func (ms *SmsSender) sender() bool {
return true
}
缺点:单一
抽象工厂模式
package factory
type factory interface {
getSender() bool
getReceiver() bool
}
// Sender 发送
type Sender interface {
sender() bool
}
// Receive 接受
type Receive interface {
receive() bool
}
type SmsSender struct {
}
func (ms *SmsSender) sender() bool {
return true
}
type MailSender struct {
}
func (ms *MailSender) sender() bool {
return false
}
type SmsReceive struct {
}
func (sr *SmsReceive) receive() bool {
return true
}
type MailReceive struct {
}
func (mr *MailReceive) receive() bool {
return true
}
type mailReceiverfactory struct {
}
func (mf *mailReceiverfactory) getReceiver() bool {
return new(MailReceive).receive()
}
type mailSenderfactory struct {
}
func (mf *mailSenderfactory) getSender() bool {
return new(MailSender).sender()
}
type smsReceiverfactory struct {
}
func (sf *smsReceiverfactory) getReceiver() bool {
return new(SmsReceive).receive()
}
type smsSenderfactory struct {
}
func (sf *smsSenderfactory) getSender() bool {
return new(SmsSender).sender()
}
总结:工厂模式与抽象工厂模式都属于创建型模式,在工厂模式中弥补了简单工厂模式的缺陷(不符合开闭原则),而在抽象工厂模式中弥补了工厂模式的不足(一个工厂只能生产一种产品)
网友评论