java 使用抽象工厂封装特性方法

1、创建抽象类:封装含有相同特性的方法。

1  */
2 public abstract class AbstractPayment {
3 
4     public abstract String progress() throws Exception;
5 
6     public abstract int notify(Map<String,String> map) throws Exception;
7 }

2、创建支付方式类继承抽象类实现具体的方法

 1  */
 2 public class AlipayWap extends AbstractPayment {
 3 
 4     @Override
 5     public String progress() throws Exception {
 6         return null;
 7     }
 8 
 9     @Override
10     public int notify(Map<String, String> map) throws Exception {
11         return 0;
12     }
13 }

3、创建支付相关工厂,初始化支付实例

 1 public class PaymentFactory {
 2 
 3     private static final Map<Integer, AbstractPayment> map = new HashMap<>();
 4     private static volatile boolean inited = false;
 5 
 6     public AbstractPayment createPayment(int type) throws Exception {
 7         if(!inited){
 8             init();
 9         }
10         AbstractPayment payment = map.get(type);
11         if(payment == null){
12 
13             System.out.println("payment ["+type+"] not exist.");
14         }
15         return payment;
16     }
17     private static void init() throws Exception {
18         AbstractPayment alipayWap = new AlipayWap();
19         map.put(1, alipayWap);
20         inited = true;
21     }
22 }

4、测试调用

1 public class Test {
2 
3     public static void main(String[] args) throws Exception {
4         AbstractPayment payment = new PaymentFactory().createPayment(1);
5         String progress = payment.progress();
6     }
7 }

 使用抽象工厂类,以后接入其他支付时。直接添加一个支付实体类ok,然后在 PaymentFactory 进行实例化即可。

原文地址:https://www.cnblogs.com/lxn0216/p/9288875.html