Java设计模式之策略模式

策略模式

Price接口
package service;

public interface Price {

    void getPross(String method);
    
}
AliPayPrice实现类
package service;

public class AliPayPrice implements Price {

    @Override
    public void getPross(String method) {
        System.out.printf("支付宝支付!");
    }
    
}
WeChatPrice实现类
package service;

public class WeChatPrice implements Price{

    @Override
    public void getPross(String method) {
        System.out.printf("微信支付!");
    }
    
}
PriceEnum枚举类
package service;

import java.util.HashMap;
import java.util.Map;

public enum PriceEnum {
    WECHAT("wechat","service.WeChatPrice"),ALIPAY("aliPay","service.AliPayPrice");

    private String method;

    private String url;

    PriceEnum(String method, String url) {
        this.method = method;
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public static Map<String,String> getAllClazz(){
        Map<String, String> map = new HashMap();
        for (PriceEnum priceEnum : PriceEnum.values()) {
            map.put(priceEnum.getMethod(),priceEnum.getUrl());
        }
        return map;
    }
}
Test测试类
package service;

import java.util.Map;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//        String method  = "wechat";
        String method  = "aliPay";
        Map<String, String> allClazz = PriceEnum.getAllClazz();
        String clazz = allClazz.get(method);
        Price price = (Price) Class.forName(clazz).newInstance();
        price.getPross(method);
    }
}

new()和newInstance()的区别

三哥的文章、策略模式https://www.yuque.com/docs/share/881fa114-0212-4235-b222-4153d33941aa?#

版权声明:
作者:黯然gg
链接:https://3zi.cn/archives/342
来源:阿龙爱吃肉
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录