zoukankan      html  css  js  c++  java
  • 设计模式-工厂模式

    设计模式-工厂模式

      工厂模式是为了解耦:把对象的创建和使用的过程分开。具体实现就是当某些方法有共同的行为,但是实现不一样,我们可以把共同的行为提成一个接口,让不同实现的类实现该接口,我们在通过一个工厂类,根据我们传入的参数进行调用我们制定的实现方法。如:支付是一种行为,具体实现有支付宝支付、微信支付、银联支付。当我们要使用支付宝支付的时候就向工厂方法传入一个参数,工厂方法通过一个参数判断调用我们指定的方法。具体代码如下:

    一、抽象公共接口(支付)

    /**
     *  @author: cyb
     *  @Date: 2020-09-24 0:14
     *  @Description:支付公共行为接口
     */
    public interface PayService {
        /***
         * 支付方法
         */
        void pay();
    }

    一、具体实现方法类一(支付宝支付)

    /**
     *  @author: cyb
     *  @Date: 2020-09-24 0:15
     *  @Description:具体实现方法-支付宝支付
     */
    public class AliPay implements PayService {
        public void pay() {
            System.out.println("支付宝支付");
        }
    }

    二、具体实现方法类二(微信支付)

    /**
     *  @author: cyb
     *  @Date: 2020-09-24 0:16
     *  @Description:支付的另一实现-微信支付
     */
    public class WeixinPay implements PayService {
        public void pay() {
            System.out.println("微信支付");
        }
    }

    三、工厂方法

    /**
     *  @author: cyb
     *  @Date: 2020-09-24 0:11
     *  @Description:创建对象工厂
     */
    public class PayFactory {
    
        public static PayService getPay(int payType){
            PayService payService=null;
            switch (payType){
                case 1:
                   return payService=new AliPay();
                case 2:
                 return    payService=new WeixinPay();
            }
            return null;
        }
    }

    四、测试方法

    public class test {
        public static void main(String[] args) {
           PayService payService= PayFactory.getPay(1);
           payService.pay();
        }
    
    }

    五、打印结果

    以上内容为本篇博客内容,后续将继续为大家分享后续设计模式。

    转载请说明出处,本人博客地址为:https://www.cnblogs.com/chenyuanbo/

  • 相关阅读:
    The Python Standard Library
    Python 中的round函数
    Python文件类型
    Python中import的用法
    Python Symbols 各种符号
    python 一行写多个语句
    免费SSL证书(https网站)申请,便宜SSL https证书申请
    元宇宙游戏Axie龙头axs分析
    OLE DB provider "SQLNCLI10" for linked server "x.x.x.x" returned message "No transaction is active.".
    The operation could not be performed because OLE DB provider "SQLNCLI10" for linked server "xxx.xxx.xxx.xxx" was unable to begin a distributed transaction.
  • 原文地址:https://www.cnblogs.com/chenyuanbo/p/13722056.html
Copyright © 2011-2022 走看看