(1):工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程屏蔽隔离起来,达到提高灵活性的目的。首先,创建二者的共同接口:
public interface Sender {
public void Send();
}
其次,创建实现类:
public class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mailsender!");
}
}
public class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
最后,建工厂类:
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) {
SendFactoryfactory = new SendFactory();
Sender sender= factory.produce("sms");
sender.Send();
}
}
输出:this is sms sender! 作者: baby14 时间: 2019-1-13 10:32
多谢分享