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?#

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇