设计模式1:工厂方法模式
工厂方法模式属于创建型设计模式,通常用于创建复杂对象。该模式将对象实例化的逻辑委托给子类来处理,即在父类中定义创建对象的接口,具体的实现由子类来完成。
在工厂方法模式中,有一个抽象的工厂接口,定义了创建对象的方法,然后不同的子类去实现这个工厂接口,从而创建不同的产品。
使用工厂方法模式的主要优点是能够降低耦合度,提高代码的可维护性和可扩展性,同时也能够方便地进行单元测试。
- 隐藏具体实现:通常来说,工厂方法模式允许创建者与消费者之间的解耦,因为消费者不需要知道具体的实现方式,只需要调用工厂方法即可。
- 可扩展性好:通过工厂方法模式,我们可以轻松地添加新的产品或者新的工厂类,而不需要修改已有的代码。
- 灵活性高:工厂方法模式可以根据需要动态地创建对象,可以通过修改对象工厂类的配置来改变创建的产品类型。
- 代码重用:通过工厂方法模式,可以避免在不同的地方重复地编写相同的代码,从而提高代码的重用率。
其缺点是会增加代码的复杂度,需要进行更多的编码工作。
示例代码
示例1
package main
import "fmt"
type Animal interface {
Name() string
Sound() string
}
type Dog struct {}
func (d *Dog) Name() string {
return "dog"
}
func (d *Dog) Sound() string {
return "bark"
}
type Cat struct {}
func (c *Cat) Name() string {
return "cat"
}
func (c *Cat) Sound() string {
return "meow"
}
type AnimalFactory interface {
Create() Animal
}
type DogFactory struct {}
func (f *DogFactory) Create() Animal {
return &Dog{}
}
type CatFactory struct {}
func (f *CatFactory) Create() Animal {
return &Cat{}
}
func Client(f AnimalFactory) Animal {
return f.Create()
}
func main() {
dogFactory := DogFactory{}
dog := Client(&dogFactory)
fmt.Println(dog.Name(), dog.Sound())
catFactory := CatFactory{}
cat := Client(&catFactory)
fmt.Println(cat.Name(), cat.Sound())
}
示例2
package main
import "fmt"
// Connection 接口定义
type Connection interface {
Connect()
}
// MySQLConnection 实现 Connection 接口
type MySQLConnection struct{}
func (c *MySQLConnection) Connect() {
fmt.Println("Connect to MySQL database...")
}
// PostgreSQLConnection 实现 Connection 接口
type PostgreSQLConnection struct{}
func (c *PostgreSQLConnection) Connect() {
fmt.Println("Connect to PostgreSQL database...")
}
// ConnectionFactory 定义工厂方法接口
type ConnectionFactory interface {
CreateConnection() Connection
}
// MySQLConnectionFactory 实现 ConnectionFactory 接口
type MySQLConnectionFactory struct{}
func (f *MySQLConnectionFactory) CreateConnection() Connection {
return &MySQLConnection{}
}
// PostgreSQLConnectionFactory 实现 ConnectionFactory 接口
type PostgreSQLConnectionFactory struct{}
func (f *PostgreSQLConnectionFactory) CreateConnection() Connection {
return &PostgreSQLConnection{}
}
func main() {
// 使用 MySQLConnectionFactory 创建 MySQLConnection 对象
mysqlFactory := &MySQLConnectionFactory{}
mysqlConn := mysqlFactory.CreateConnection()
mysqlConn.Connect()
// 使用 PostgreSQLConnectionFactory 创建 PostgreSQLConnection 对象
postgresFactory := &PostgreSQLConnectionFactory{}
postgresConn := postgresFactory.CreateConnection()
postgresConn.Connect()
}