网站线框图怎么做,福田网站建设方案服务,济南城市建设集团 网站,app与网站的关系目录
工厂方法模式#xff08;Factory Method Pattern#xff09;
工厂模式的核心角色
优缺点
代码实现 工厂方法模式#xff08;Factory Method Pattern#xff09; 工厂方法模式#xff08;Factory Method Pattern#xff09;又叫作多态性工厂模式#xff0c;指的…目录
工厂方法模式Factory Method Pattern
工厂模式的核心角色
优缺点
代码实现 工厂方法模式Factory Method Pattern 工厂方法模式Factory Method Pattern又叫作多态性工厂模式指的是定义一个创建对象的接口但由实现这个接口的工厂类来决定实例化哪个产品类工厂方法把类的实例化推迟到子类中进行。在工厂方法模式中不再由单一的工厂类生产产品而是由工厂类的子类实现具体产品的创建。因此当增加一个产品时只需增加一个相应的工厂类的子类, 以解决简单工厂生产太多产品时导致其内部代码臃肿switch … case分支过多的问题。(注意Go中没有继承所以这里说的工厂子类其实是直接实现工厂接口的具体工厂类。) 工厂方法模式在Go语言中有着广泛的应用例如在数据库访问、消息队列、日志记录等方面都可以使用工厂方法模式来创建对象实例以实现更加灵活和可扩展的代码。
工厂模式的核心角色 1、抽象产品Abstract Product定义了产品的共同接口或抽象类。它可以是具体产品类的父类或接口规定了产品对象的共同方法。 2、具体产品Concrete Product实现了抽象产品接口定义了具体产品的特定行为和属性。 3、抽象工厂Abstract Factory声明了创建产品的抽象方法可以是接口或抽象类。它可以有多个方法用于创建不同类型的产品。 4、具体工厂Concrete Factory实现了抽象工厂接口负责实际创建具体产品的对象。
优缺点
1优点
灵活性增强对于新产品的创建只需多写一个相应的工厂类。
典型的解耦框架。高层模块只需要知道产品的抽象类无须关心其他实现类满足迪米特法则、依赖倒置原则和里氏替换原则。
2缺点
类的个数容易过多增加复杂度。
增加了系统的抽象性和理解难度。
只能生产一种产品此弊端可使用抽象工厂模式解决。
代码实现
package mainimport fmt// (抽象产品)MathOperator 实际产品实现的接口--表示数学运算器应该有哪些行为
type MathOperator interface {SetOperandA(int)SetOperandB(int)ComputerResult() int
}// 具体产品PlusOperator 实际的产品类--加法运算器
type PlusOperator struct {operandA intoperandB int
}func (po *PlusOperator) SetOperandA(operand int) {po.operandA operand
}
func (po *PlusOperator) SetOperandB(operand int) {po.operandB operand
}
func (po *PlusOperator) ComputerResult() int {return po.operandA po.operandB
}// (具体产品)MultiOperator 实际的产品类--乘法运算器
type MultiOperator struct {operandA intoperandB int
}
func (mo *MultiOperator) SetOperandA(operand int) {mo.operandA operand
}
func (mo *MultiOperator) SetOperandB(operand int) {mo.operandB operand
}
func (mo *MultiOperator) ComputerResult() int {return mo.operandA * mo.operandB
}// 抽象工厂OperatorFactory 工厂接口由具体工厂类来实现
type OperatorFactory interface {Create() MathOperator
}// 假定程序可以生产两类计算器加法计算器和乘法计算器也就是在工厂方法模式中存在两个子类工厂。
// 具体工厂PlusOperatorFactory 是 PlusOperator 加法运算器的工厂类
type PlusOperatorFactory struct {
}func (pof *PlusOperatorFactory) Create() MathOperator {return PlusOperator{operandA: 1,operandB: 2,}
}// (具体工厂)MultiOperatorFactory 是乘法运算器产品的工厂
type MultiOperatorFactory struct {
}func (mof *MultiOperatorFactory) Create() MathOperator {return MultiOperator{operandA: 1,operandB: 2,}
}func main() {// 使用工厂方法模式时客户端代码只需要调用工厂接口的方法而无需关心具体的产品对象是如何创建的。factory : PlusOperatorFactory{}plus : factory.Create()plus.SetOperandA(2)plus.SetOperandB(3)fmt.Printf(%v\n, plus.ComputerResult())factorym : MultiOperatorFactory{}multi : factorym.Create()multi.SetOperandA(1)multi.SetOperandB(3)fmt.Printf(%v\n, multi.ComputerResult())
}