JAVA设计模式-工厂模式
# JAVA设计模式-工厂模式
# 简单工厂模式
# 介绍
简单工厂模式就是定义一个工厂类,工厂类提供获取实例的方法,方法会根据传入的参数不同来返回不同的实例。不同的实例基本都有共同的父类。对于下面的例子里面增加新的动物需要修改代码,否则无法扩展。
# 代码示例
/**
* 接口定义
*/
interface Animal {
void eat();
}
/**
* 实现类
*/
class Dog implements Animal{
public void eat() {
}
}
/**
* 实现类
*/
class Cat implements Animal{
public void eat() {
}
}
class AnimalFactory{
public static Animal createAnimal(String type){
if("Cat".equals(type)){
return new Cat();
} else if("Dog".equals(type)){
return new Dog();
}
return null;
}
}
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
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
# 工厂方法模式
# 介绍
工厂方法模式和简单工厂模式区别,简单工厂模式工厂类只有一个,工厂方法模式可能有一个或者多个,它们都是实现了相同接口的一组工厂类。
# 代码示例
/**
* 接口定义
*/
interface Animal {
void eat();
}
/**
* 实现类
*/
class Dog implements Animal{
public void eat() {
}
}
/**
* 实现类
*/
class Cat implements Animal{
public void eat() {
}
}
/**
* 接口定义
*/
interface AnimalFactory {
Animal createAnimal();
}
/**
* 实现类
*/
class DogFactory implements AnimalFactory{
public Animal createAnimal() {
return new Dog();
}
}
/**
* 实现类
*/
class CatFactory implements AnimalFactory{
public Animal createAnimal() {
return new Cat();
}
}
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
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
# 抽象工厂模式
# 介绍
抽象工厂模式可以理解成创建工厂的工厂,每一个生成的工厂又可以按照工厂模式创建对象。这里面其实有一个产品族的概念,产品族是不同的一组产品等级结构的一组产品。还有产品等级结构等概念,这里就不过多展开了。抽象工厂模式可以理解为解决两个维度组合产品的构造问题,取其中一个维度作为产品族,另一个维度作为产品族中的具体的多个产品。
# 代码示例
interface Dog {
void eat();
}
class BlackDog implements Dog{
public void eat() {
}
}
class WhiteDog implements Dog{
public void eat() {
}
}
interface Cat {
void eat();
}
class BlackCat implements Cat{
public void eat() {
}
}
class WhiteCat implements Cat{
public void eat() {
}
}
interface AnimalFactory {
Dog createGog();
Cat createCat();
}
class WhiteAnimalFactory implements AnimalFactory{
public Dog createGog() {
return new WhiteDog();
}
public Cat createCat() {
return new WhiteCat();
}
}
class BlackAnimalFactory implements AnimalFactory{
public Dog createGog() {
return new BlackDog();
}
public Cat createCat() {
return new BlackCat();
}
}
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
53
54
55
56
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
53
54
55
56
# 小结
工厂方法模式只有一个抽象产品类,可以有多个具体的产品类去实现,工厂类类似,只有一个抽象的工厂类,可以有多个具体的工厂类去实现,每一个具体的工厂类只能创建一个具体的产品类的实例。
抽象工厂模式有多个抽象的产品类,每个抽象的产品类可以有多个具体的产品类去实现,但是只有一个抽象的工厂类,这个工厂类可以有多个具体的工厂类去实现,每个具体的工厂类可以创建多个具体的产品类的实例。
编辑 (opens new window)
上次更新: 2023/02/26, 10:03:01