工厂模式-工厂方法模式

简单工厂和工厂方法

image.png

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
47
48
49
50
51
52
/**
* 工厂方法
*/
public class FactoryMethodModelTest {
public static void main(String[] args) {
Product a = new FactoryMethodA().createProduct();
a.doProduct();
Product b = new FactoryMethodB().createProduct();
b.doProduct();
}
}


interface Product {
void doProduct();
}

class ProductA implements Product {

@Override
public void doProduct() {
System.out.println("I am ProductA.");
}
}

class ProductB implements Product {

@Override
public void doProduct() {
System.out.println("I am ProductB.");
}
}

interface FactoryMethod {
Product createProduct();
}

class FactoryMethodA implements FactoryMethod {

@Override
public Product createProduct() {
return new ProductA();
}
}

class FactoryMethodB implements FactoryMethod {

@Override
public Product createProduct() {
return new ProductB();
}
}

工厂模式-工厂方法模式
https://leehoward.cn/2023/05/01/工厂模式-工厂方法模式/
作者
lihao
发布于
2023年5月1日
许可协议