工厂方法模式
352 words
One minute
- 特点:
- 优点:
- 新增产品是新增对应的工厂和产品就好了, 不用修改原有的工厂类, 产品之间的创建逻辑解耦
- 缺点:
- 新增产品需要新增产品和工厂类, 比较麻烦, 因为一个产品对应一个类, 产品较多时类会很多
Goalng 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| package factory_method
import "fmt"
// 抽象
type AbstractProduct interface {
Show()
}
type AbstractFactory interface {
CreateProduct() *AbstractProduct
}
// 实现
type ProductA struct {}
func (p ProductA) Show() {
fmt.Println("ProductA Show")
}
type ProductB struct {}
func (p ProductB) Show() {
fmt.Println("ProductB Show")
}
type FactoryA struct {}
func (f FactoryA) CreateProduct() AbstractProduct {
return &ProductA{}
}
type FactoryB struct {}
func (f FactoryB) CreateProduct() AbstractProduct {
return &ProductB{}
}
// 业务
/*
productA := new(FactoryA).CreateProduct()
productA := new(FactoryB).CreateProduct()
*/
|
TypeScript 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| interface Product {
useFunction(): void;
}
class ProductA implements Product {
public useFunction(){
console.log("ProductA useFunction")
}
}
class ProductB implements Product {
public useFunction(){
console.log("ProductB useFunction")
}
}
abstract class Factory {
public abstract createProduct(): Product;
}
class ProductAFactory extends Factory {
public createProduct(): Product {
return new ProductA();
}
}
class ProductBFactory extends Factory {
public createProduct(): Product {
return new ProductB();
}
}
const productAFactory = new ProductAFactory()
productAFactory.createProduct().useFunction()
const productBFactory = new ProductBFactory()
productBFactory.createProduct().useFunction()
|