• 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 进行实例化即可。

  • 相关阅读:
    XML 命名空间
    XML Schema验证
    java 解析XML文档
    Java线程:创建与启动
    CCF-CSP 201312-5 I'm stuck !
    memset函数用法
    C++的字符串多行输入
    OS复习1
    os复习2
    javamail编程2
  • 原文地址:https://www.cnblogs.com/lxn0216/p/9288875.html
Copyright © 2020-2023  润新知