简单的工厂模式

图:简单的工厂模式、多个工厂方法模式、静态工厂模式 的结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface Sender {
public void Send();
}

public class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mail sender!");
}
}

public class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
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;
}
}
}

多个工厂方法模式

图:静态工厂模式、抽象工厂模式、简单的工厂模式 的结构。

​ 该模式是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象。

1
2
3
4
5
6
7
8
9
 public class SendFactory {
public Sender produceMail(){
return new MailSender();
}

public Sender produceSms(){
return new SmsSender();
}
}
1
2
3
4
5
6
7
 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
public class SendFactory {
public static Sender produceMail(){
return new MailSender();
}

public static Sender produceSms(){
return new SmsSender();
}
}
1
2
3
4
5
6
 public class FactoryTest {
public static void main(String[] args) {
Sender sender = SendFactory.produceMail();
sender.send();
}
}

抽象工厂模式

图:静态工厂模式、抽象工厂模式、简单的工厂模式 的结构。

​ 工厂方法模式有一个问题就是,类的创建依赖工厂类,也就是说,如果想要拓展程序,必须对工厂类进行修改,这违背了闭包原则,所以,从设计角度考虑,有一定的问题,如何解决?
​ 这就用到抽象工厂模式,创建多个工厂类,这样一旦需要增加新的功能,直接增加新的工厂类就可以了,不需要修改之前的代码。

​ 一个多态和反多态的体现:

1
2
3
4
5
6
7
8
9
10
//工厂接口
public interface Provider {
//返回值为Sender
public Sender produce();
}

//工厂产品接口(发送方式)
public interface Sender {
public void send();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class MailSender implements Sender {
@Override
public void send() {
System.out.println("this is mail sender!");
}
}

public class SmsSender implements Sender {
@Override
public void send() {
System.out.println("this is sms sender!");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class SendSmsFactory implements Provider {
@Override
public Sender produce() {
return new SmsSender();
}
}

public class SendMailFactory implements Provider {
@Override
public Sender produce() {
return new MailSender();
}
}
1
2
3
4
5
6
7
8
public class Test {
public static void main(String[] args) {
//多态
Provider provider = new SendMailFactory();
Sender sender = provider.produce();
sender.send();
}
}