Java设计模式系列2--工厂方法模式(Factory Method)

2014-02-26 09:56:45

声明:本文不仅是本人自己的成果,有些东西取自网上各位大神的思想,虽不能一一列出,但在此一并感谢!

工厂方法模式分为三种:

1. 普通工厂模式

建立一个工厂类,对实现了同一接口的一些类进行实例的创建,如下图:

Java设计模式系列2--工厂方法模式(Factory Method)

代码示例如下:

 public interface Sender {
public void send();
} class MailSender implements Sender { @Override
public void send() {
System.out.println("This is MailSender!");
}
} class SmsSender implements Sender { @Override
public void send() {
System.out.println("This is SmsSender!");
}
} 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;
}
}
}

2. 多个工厂方法模式

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

Java设计模式系列2--工厂方法模式(Factory Method)

代码示例如下:

 public interface Sender {
public void send();
} class MailSender implements Sender { @Override
public void send() {
System.out.println("This is MailSender!");
}
} class SmsSender implements Sender { @Override
public void send() {
System.out.println("This is SmsSender!");
}
} class SendFactory { public Sender produceMail() {
return new MailSender();
} public Sender produceSms() {
return new SmsSender();
}
}

3. 静态工厂方法模式

将上面的多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可。

代码示例如下:

 public interface Sender {
public void send();
} class MailSender implements Sender { @Override
public void send() {
System.out.println("This is MailSender!");
}
} class SmsSender implements Sender { @Override
public void send() {
System.out.println("This is SmsSender!");
}
} class SendFactory { public static Sender produceMail() {
return new MailSender();
} public static Sender produceSms() {
return new SmsSender();
}
}

总体来说,凡是出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建。在以上的三种模式中,第一种如果传入的字符串有误,不能正确创建对象,第三种相对于第二种,不需要实例化工厂类,所以,大多数情况下,我们会选用第三种——静态工厂方法模式。

上一篇:MST:Out of Hay(POJ 2395)


下一篇:spring data jpa 一对多查询