简单工厂方法,举例:有一个数据访问层的工厂类DAOFactory(接口),里面有各种数据库的实现,例如:OracleDAOFactory和MysqlDAOFactory,然后可以根据你在客户端的输入或者某个配置文件的信息:“ORACLE”或者"MYSQL",去创建属于自己需要的那个数据库实现:DAOFactory df = (DAOFactory)Class.forName("OracleDAOFactory类全名").newInstance();达到降低程序耦合性的目的。
抽象工厂模式用法就相对复杂,例:我要进行农行ABC和工行ICBC的在线支付,每个在线支付有pay付款和verify验证俩个动作,但农行的支付是不能和工行的验证放一起的。coding说明:
1、先定义抽象工厂:AbstractFactory(),里面俩个方法用于获得支付行为,和验证行为。
public interface AbstractFactory {
public abstract PayAction createPayAction();
public abstract VerifyAction createVerifyAction();
}
2、再定义俩个银行,实现抽象工厂:
public class ABCFactory implements AbstractFactory{
@Override
public PayAction createPayAction() {
// TODO Auto-generated method stub
return new ABCPayAction();
}
@Override
public VerifyAction createVerifyAction() {
// TODO Auto-generated method stub
return new ABCVerifyAction();
}
}
public class ICBCFactory implements AbstractFactory{
@Override
public PayAction createPayAction() {
// TODO Auto-generated method stub
return new ICBCPayAction();
}
@Override
public VerifyAction createVerifyAction() {
// TODO Auto-generated method stub
return new ICBCVerifyAction();
}
}
3、然后创建支付行为类,和验证行为类:
public interface PayAction{
public void doPay();
}
public interface VerifyAction {
public void doVerify();
}
4、因为每个银行的支付信息和验证信息不同,所以农行行为和工行行为分别实现各自的支付动作和验证动作。
农行的支付和验证:
public class ABCPayAction implements PayAction {
@Override
public void doPay() {
System.out.println("this is abc pay!");
}
}
public class ABCVerifyAction implements VerifyAction{
@Override
public void doVerify() {
System.out.println("this is abc verify!");
}
}
工行的支付和验证:
public class ICBCPayAction implements PayAction {
@Override
public void doPay() {
System.out.println("this is icbc pay!");
}
}
public class ICBCVerifyAction implements VerifyAction {
@Override
public void doVerify() {
System.out.println("this is icbc verify!");
}
}
5、然后消费者Buyer开始消费,创建消费者类:
public class Buyer {
private PayAction pa= null;
private VerifyAction va = null;
public void doBuy(AbstractFactory af){
this.pa = af.createPayAction();
this.va =af.createVerifyAction();
this.pa.doPay();
this.va.doVerify();
}
}
6、都ok了,就开始客户端测试
public class Cilent {
public static void main(String[] args) {
Buyer b = new Buyer();
b.doBuy(new ABCFactory());
//b.doBuy(new ICBCFactory());
}
}
结果:
this is abc pay!
this is abc verify!
本文通过具体实例介绍了抽象工厂模式和简单工厂模式的使用方法,包括如何在不同银行在线支付场景中应用这些模式以实现解耦和灵活的业务逻辑扩展。

419

被折叠的 条评论
为什么被折叠?



