抽象工厂模式
由于普通工厂模式,较多的依赖于工厂类,如果增加功能的话改动较大,我们来看看抽象工厂模式的实现方法
1.创建一个接口,这个接口由实现类来实现
public interface ISender {
public void Send();
}
2.实现类
public class MailSender implements ISender {
@Override
public void Send() {
System.out.println("this is mailsender!");
}
}
public class SmsSender implements ISender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
3.分别创建两个发送短信和发送邮件的工厂类
public class SendMailFactory implements IProvider {
@Override
public ISender produce(){
return new MailSender();
}
}
public class SendSmsFactory implements IProvider{
@Override
public ISender produce() {
return new SmsSender();
}
}
4.创建一个工厂类的接口
public interface IProvider {
public ISender produce();
}
5.测试
public class Test {
public static void main(String[] args) {
IProvider provider = new SendMailFactory();
ISender sender = provider.produce();
sender.Send();
}
}