我们来看一下发送电子邮件和短信代码
创建二者的共同接口Sender
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) {
// TODO Auto-generated method stub
SendFactory factory=new SendFactory();
Sender sender=factory.produce("sms");
sender.Send();
}
}
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) {
// TODO Auto-generated method stub
SendFactory factory=new SendFactory();
Sender sender=factory.produce("sms");
sender.Send();
}
}
我们更改工厂代码
public class SendFactory {
public Sender produceMail(){
return new MailSender();
}
public Sender produceSms(){
return new SmsSender();
}
}
测试代码
public class FactoryTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
SendFactory factory=new SendFactory();
Sender sender=factory.produceMail();
sender.Send();
}
}
输出结果:发送邮件
静态工厂方法模式,将上面的多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可
其他类代码我们不变我们更改测试类代码
public class FactoryTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sender sender=SendFactory.produceMail();
sender.Send();
}
}
总体来说,工厂模式适合:凡是出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建。在以上的三种模式中,第一种如果传入的字符串有
工厂方法模式(Factory Method)工厂方法模式分为三种:普通工厂模式,就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。我们来看一下发送电子邮件和短信代码创建二者的共同接口Senderpublic interface Sender { public void Send();}创建两个实现类public class MailSender implements S