设计模式——工厂模式

概述

用模板方法来构建生成实例的工厂, 这就是工厂方法模式

类图

Product

1
2
3
4
5
6
7
8
9
10
package com.example.factory.framework;

/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-10-06
*/
public abstract class Product {
public abstract void use();
}

Factory

只要是工厂方法模式, 在生成实例时就一定会使用到模板方法模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.example.factory.framework;

/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-10-06
*/
public abstract class Factory {

public final Product create(String owner) {
Product p = createProduct(owner);
registerProduct(p);
return p;
}

protected abstract void registerProduct(Product p);

protected abstract Product createProduct(String owner);
}

IDCard

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
package com.example.factory.idcard;

import com.example.factory.framework.Product;

/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-10-06
*/
public class IDCard extends Product {

private String owner;

public IDCard(String owner) {
System.out.println("制作" + owner + "的ID卡。");
this.owner = owner;
}

@Override
public void use() {
System.out.println("使用" + owner + "的ID卡。");
}

public String getOwner() {
return owner;
}
}

IDCardFactory

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
package com.example.factory.idcard;

import com.example.factory.framework.Factory;
import com.example.factory.framework.Product;

import java.util.ArrayList;
import java.util.List;

/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-10-06
*/
public class IDCardFactory extends Factory {

private List owners = new ArrayList();

@Override
protected void registerProduct(Product p) {
owners.add(((IDCard)p).getOwner());
}

@Override
protected Product createProduct(String owner) {
return new IDCard(owner);
}

public List getOwners() {
return owners;
}
}

测试

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
package com.example.factory;

import com.example.factory.framework.Product;
import com.example.factory.idcard.IDCardFactory;

/**
* @author 当我遇上你
* @公众号 当我遇上你
* @since 2020-10-06
*/
public class FactoryDemo {

/**
* 制作张三的ID卡。
* 制作李四的ID卡。
* 制作王五的ID卡。
* 使用张三的ID卡。
* 使用李四的ID卡。
* 使用王五的ID卡。
*
* @param args
*/
public static void main(String[] args) {
IDCardFactory factory = new IDCardFactory();
Product card1 = factory.create("张三");
Product card2 = factory.create("李四");
Product card3 = factory.create("王五");
card1.use();
card2.use();
card3.use();

}
}

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。