zoukankan      html  css  js  c++  java
  • 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 进行实例化即可。

  • 相关阅读:
    图像和流媒体 -- 帧率、分辨率、码流的概念和关系(转)
    Linux设备驱动(转)
    STM32开发 -- 4G模块开发详解(转)
    Linux下EC20实现ppp拨号(转)
    使用机智云APP控制战舰V3 (转)
    USB Host读取U盘成功
    FreeModbus在STM32上移植(转)
    处理分页操作
    HBase参数配置及说明(转)
    学习JNDI
  • 原文地址:https://www.cnblogs.com/lxn0216/p/9288875.html
Copyright © 2011-2022 走看看