简单工厂其实不是一个设计模式,它是一种编程习惯。由于经常被使用,它被誉为“Head First Pattern荣誉讲”。有些开发人月经常把这个编程习惯当作“工厂模式”。
简单工厂的有点就是把创建对象放在SimplaFactory中,当我们需要某个对象时,不用关心对象的创建细节。
当我们在做订单支付的时候,需要对接微信、支付宝、建行等支付方式,这个时候我们就可以使用简单工厂来处理。
首先创建一个支付接口,并定义了预下单的方法。
package toolkit.net.cn;
/**
* 支付接口
* @author zhaox
*/
public interface Payment {
/**
* 统一下单
* @return
*/
public boolean order();
}
实现微信、支付宝、建行支付,对应的具体类
package toolkit.net.cn;
/**
* 微信支付,统一下单
* @author zhaox
*/
public class WxPay implements Payment {
/**
* 统一下单
*
* @return
*/
@Override
public boolean order() {
System.out.println("微信统一下单");
return true;
}
}
package toolkit.net.cn;
/**
* 支付宝
* @author zhaox
*/
public class AliPay implements Payment{
/**
* 统一下单
*
* @return
*/
@Override
public boolean order() {
System.out.println("支付宝预下单");
return true;
}
}
package toolkit.net.cn;
/**
* 建行支付
* @author zhaox
*/
public class CcbPay implements Payment{
/**
* 统一下单
*
* @return
*/
@Override
public boolean order() {
System.out.println("建行统一下单");
return true;
}
}
建立一个简单的支付工厂,定义一个类,为所有的支付方式创建对象。代码像这样......
package toolkit.net.cn;
/**
* 简单工厂
* @author zhaox
*/
public class SimplePaymentFactory {
private Payment payment;
public Payment build(String type) {
// 微信
if ("wx".equals(type)) {
payment = new WxPay();
} else if ("ali".equals(type)) {
// 支付宝
payment = new AliPay();
} else if ("ccb".equals(type)) {
// 建行
payment = new CcbPay();
}
return payment;
}
}
仰仗工厂来创建对应的支付方式
package toolkit.net.cn;
/**
* @author zhaox
*/
public class Main {
public static void main(String[] args) {
SimplePaymentFactory simplePaymentFactory = new SimplePaymentFactory();
Payment payment = simplePaymentFactory.build("wx");
payment.order();
}
}
工厂处理了对象的创建细节,一旦有了SimplePaymentFactory,当需要支付时,就叫简单支付工厂创建一个。我们之关系从工厂得到一个支付对象,而这些支付对象都实现了Payment接口,所以可以直接调用order()方法进行预下单。
这样做的好处是:我们把创建不同支付对象的代码包装进了一个类,当以后实现发生改变时,只需要修改这个类。