设计模式之工厂模式

Author Avatar
Sarience 5月 17, 2017
  • 在其它设备中阅读本文章

工厂方法模式分为三种:普通工厂模式 多个工厂方法模式 静态工厂方法模式

普通工厂

就是建立一个工厂类,对实现了同一接口的产品类进行实例的创建(工厂类根据不同的参数返回不同的对象)
例如:

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
//发送短信和邮件的接口
public interface Sender {
public void Send();
}
//发送邮件的实现类
public class MailSender implements Sender {
public void Send() {
System.out.println("发送邮件!");
}
}
//发送短信的实现类
public class SmsSender implements Sender {
public void Send() {
System.out.println("发送短信!");
}
}
//创建工厂类
public class SendFactory {
//工厂方法
public Sender produce(String type) {
if ("mail".equals(type)) {
return new MailSender();
} else if ("sms".equals(type)) {
return new SmsSender();
} else {
System.out.println("请输入正确的类型!");
return null;
}
}
}
//测试类
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender = factory.produce("sms");
sender.Send();
}
}

多个工厂方法模式

是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象。(顾名思义,就是在工厂类中定义多个方法,每个方法返回一个对象,也可以简单的理解为普通工厂是根据参数返回不同对象,而多个工厂方法是根据方法返回不同对象)

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//将上面的代码做下修改,改动下SendFactory类就行
//这个就不用根据用户传的字符串类创建对象了
public class SendFactory {
public Sender produceMail(){
return new MailSender();
}
public Sender produceSms(){
return new SmsSender();
}
}
//测试类
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender = factory.produceMail();
sender.Send();
}
}

静态工厂方法模式

将上面的多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可。(可以看做是多工厂方法模式的升级版,将工厂类方法声明为静态的,那么就不需要创建工厂实例,直接调用方法即可)

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class SendFactory {
public static Sender produceMail(){
return new MailSender();
}
public static Sender produceSms(){
return new SmsSender();
}
}
//测试类
public class FactoryTest {
public static void main(String[] args) {
Sender sender = SendFactory.produceMail();
sender.Send();
}
}