2.2.5 抽象工厂模式
(1)类图结构
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d76066f3fe3ac14f0c3730e7adfe257e.png#pic_center)
(2)代码演示
public interface Sender {
void send();
}
public class MailSender implements Sender{
@Override
public void send() {
System.out.println("正在发送邮件...");
}
}
public class SmsSender implements Sender{
@Override
public void send() {
System.out.println("正在发送短信...");
}
}
public class PacketSender implements Sender{
@Override
public void send() {
System.out.println("正在发送包裹...");
}
}
public interface Provider {
Sender produce();
}
public class MailSendFactory implements Provider{
@Override
public Sender produce() {
return new MailSender();
}
}
public class SmsSendFactory implements Provider {
@Override
public Sender produce() {
return new SmsSender();
}
}
public class PacketSendFactory implements Provider {
@Override
public Sender produce() {
return new PacketSender();
}
}
public class SendFactoryTest {
public static void main(String[] args) {
Provider provider=new MailSendFactory();
Sender sender2 = provider.produce();
sender2.send();
System.out.println("----------------------------");
Provider provider1=new PacketSendFactory();
Sender sender3 = provider1.produce();
sender3.send();