简单工厂和抽象工厂模式的理解

  简单工厂方法,举例:有一个数据访问层的工厂类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!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值