工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法模式使一个类的实例化延迟到其子类。
1)普通工厂方法模式
建立一个工厂类,对实现了同一接口的一些类进行实例的创建,如图10-2所示。
图10-2 普通工厂方法模式示例
举一个现金付款和信用卡付款的例子。
首先,创建两者的共同接口:
public interface Payer{
public void pay();
}
其次,创建实现类:
public class CashPayer implements Payer{
@Override
public void Pay(){
System.out.println("this is Cash Payer!");
}
}
public class CreditCardPayer implements Payer{
@Override
public void Pay(){
System.out.println("this is CreditCard Payer!");
}
}
最后,创建工厂类:
public class PayFactory{
public Payer produce(String type){
if("cash".equals(type)){
return new CashPayer();
}else if("creditcard".equals(type)){
return new CreditCardPayer();
}else{
System.out.println("请输入正确的类型!");
return null;
}
}
}
测试:
public class FactoryTest{
public static void main(String[]args){
PayFactory factory=new PayFactory();
Payer Payer=factory.produce("creditcard");
Payer.pay();
}
}
输出:(www.xing528.com)
this is CreditCard Payer!
2)多个工厂方法模式
这个工厂方法模式是对普通工厂方法模式的改进。在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式提供多个工厂方法,可分别创建对象。类之间的关系如图10-3所示。
图10-3 多个工厂方法模式示例
对之前的代码改动PayFactory类如下:
public class PayFactory{
public Payer produceCashP(){
return new CashPayer();
}
public Payer produceCreditCardP(){
return new CreditCardPayer();
}
}
测试:
public class FactoryTest{
public static void main(String[]args){
PayFactory factory=new PayFactory();
Payer Payer=factory.produceCashP();
Payer.pay();
}
}
输出:
this is CashPayer!
3)静态工厂方法模式
将多个工厂方法模式里的方法置为静态,不需要创建实例,直接调用即可。
public class PayFactory{
public static Payer produceCashP(){
return new CashPayer();
}
public static Payer produceCreditCardP(){
return new CreditCardPayer();
}
}
public class FactoryTest{
public static void main(String[]args){
Payer Payer=PayFactory.produceCashP();
Payer.pay();
}
}
输出:
this is CashPayer!
总体来说,工厂模式适合使用的情况是:出现了大量的对象需要创建,并且具有共同的接口。在上面的三种模式中,在第一种模式中如果传入的字符串有误,则不能正确创建对象;第三种相对于第二种,不需要实例化工厂类。所以,大多数情况下,建议选用第三种模式——静态工厂方法模式。
免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。