策略模式实现方式之Map<K,Function>

本文介绍了如何使用策略模式实现对象行为的多种表现形式,通过Map<K,Function>封装不同的功能函数,以及利用Java多态和接口实现的示例。主要展示了如何根据场景选择不同的行为执行逻辑。
摘要由CSDN通过智能技术生成

策略模式实现方式之Map<K,Function>

小概念

场景

  • 我们有一个对象
  • 对象有一个行为
  • 该行为在不同场景中有不同的表现形式

策略模式

  • 定义了一系列算法
  • 封装了每个算法
  • 这一系列的算法可互换代替

代码实现

定义一个对象行为表现形式枚举

    //定义一个对象行为表现形式枚举
    public enum AdApplyTypeEnum implements BaseEnum<Integer> {

    /**
     * 价值鉴定
     */
    WORTH(1, "价值鉴定","JZJD",3);

    Integer value;

    /**
     * 名称
     */
    String name;

    /**
     * 申请单编号编码前缀
     */
    String code;

    /**
     * 鉴定类型对应工作流模板类型
     */
    Integer wfType;

    AdApplyTypeEnum(Integer value, String name, String code,Integer wfType) {
        this.value = value;
        this.name = name;
        this.code = code;
        this.wfType = wfType;
    }

    /**
     * 获取枚举值
     *
     * @return value
     */
    @Override
    public Integer getValue() {
        return value;
    }

    /**
     * 根据枚举值获取枚举类型
     *
     * @param value 枚举值
     * @return FormStateEnum
     */
    public static AdApplyTypeEnum valueOf(Integer value) {
        for (AdApplyTypeEnum typeEnum : AdApplyTypeEnum.values()) {
            if (typeEnum.getValue().equals(value)) {
                return typeEnum;
            }
        }
        return AdApplyTypeEnum.OTHER;
    }
}

定义每种表现形式

/**
 *价值
 **/
private boolean updateWorth(AdApplyDataPO adApplyDataPO) {

}
/**
 * 销毁
 **/
private boolean updateDestroy(AdApplyDataPO adApplyDataPO) {
        
}

封装Map<K,Funtion> 和 初始化算法的对应的函数

    /**
     * 鉴定完成业务逻辑
     */
    private final Map<AdApplyTypeEnum, Function<AdApplyDataPO, Boolean>> applyTypeBusinessLogicMap = new HashMap<>(16);

    /**
     * 初始化鉴定类型对应鉴定完成后业务逻辑
     */
    @PostConstruct
    private void initApplyTypeBusinessLogicMap() {
        applyTypeBusinessLogicMap.put(AdApplyTypeEnum.WORTH, this::updateWorth);
        applyTypeBusinessLogicMap.put(AdApplyTypeEnum.DESTROY, this::updateDestroy);
        applyTypeBusinessLogicMap.put(AdApplyTypeEnum.DECRYPT, this::updateDecrypt);
        applyTypeBusinessLogicMap.put(AdApplyTypeEnum.OPEN, this::updateOpen);
    }

具体应用

    //参数
    AdApplyDataPO adApplyDataPO;
    //K值
    AdApplyTypeEnum adApplyType;
    //调用
    applyTypeBusinessLogicMap.get(adApplyType).apply(adApplyDataPO);

其他实现方式

利用java的多态特性

  • 使用接口的多实现
  • 子类继承父类重写父类的方法
代码实现
//StrategyExample test application

class StrategyExample {

    public static void main(String[] args) {

        Context context;

        // Three contexts following different strategies
        context = new Context(new FirstStrategy());
        context.execute();

        context = new Context(new SecondStrategy());
        context.execute();

        context = new Context(new ThirdStrategy());
        context.execute();

    }

}

// The classes that implement a concrete strategy should implement this

// The context class uses this to call the concrete strategy
interface Strategy {

    void execute();
    
}

// Implements the algorithm using the strategy interface
class FirstStrategy implements Strategy {

    public void execute() {
        System.out.println("Called FirstStrategy.execute()");
    }
    
}

class SecondStrategy implements Strategy {

    public void execute() {
        System.out.println("Called SecondStrategy.execute()");
    }
    
}

class ThirdStrategy implements Strategy {

    public void execute() {
        System.out.println("Called ThirdStrategy.execute()");
    }
    
}

// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {

    Strategy strategy;

    // Constructor
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void execute() {
        this.strategy.execute();
    }

}

还有一种在枚举中实现

但是这种我很少见到别人使用,不知道是不符合规范还是什么原因
不知道还有没有其他更好用的方式了

实现示例
enum PaymentStrategy {
    CREDIT_CARD {
        @Override
        void pay(int amount) {
            System.out.println("Paid " + amount + " dollars by credit card");
        }
    },
    PAYPAL {
        @Override
        void pay(int amount) {
            System.out.println("Paid " + amount + " dollars by PayPal");
        }
    };

    abstract void pay(int amount);
}

public class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int amount) {
        paymentStrategy.pay(amount);
    }

    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        cart.setPaymentStrategy(PaymentStrategy.CREDIT_CARD);
        cart.checkout(100);

        cart.setPaymentStrategy(PaymentStrategy.PAYPAL);
        cart.checkout(50);
    }
}
你可以使用Java的Collections工具中的sort方法来对List<Map<>>进行排序。首先,你需要实现一个Comparator接口,用于定义Map的比较规则。然后,使用Collections的sort方法,并传入你实现的Comparator对象作为参数,就可以对List<Map<>>进行排序了。 以下是一个示例代码,演示如何对List<Map<>>按照Map中的某个键值进行排序: ```java import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; public class MapSortExample { public static void main(String[] args) { List<Map<String, Integer>> list = getList(); // 假设你已经有一个List<Map<String, Integer>>对象 // 对List<Map<>>进行排序 Collections.sort(list, new Comparator<Map<String, Integer>>() { @Override public int compare(Map<String, Integer> map1, Map<String, Integer> map2) { // 这里假设你要按照Map中的键 "key" 进行升序排序 Integer key1 = map1.get("key"); Integer key2 = map2.get("key"); return key1.compareTo(key2); } }); // 输出排序后的结果 for (Map<String, Integer> map : list) { System.out.println(map); } } // 获取一个示例的List<Map<>> private static List<Map<String, Integer>> getList() { // 这里只是一个示例,你可以根据实际需求构造自己的List<Map<>> List<Map<String, Integer>> list = new ArrayList<>(); Map<String, Integer> map1 = new HashMap<>(); map1.put("key", 3); map1.put("value", 100); list.add(map1); Map<String, Integer> map2 = new HashMap<>(); map2.put("key", 1); map2.put("value", 200); list.add(map2); Map<String, Integer> map3 = new HashMap<>(); map3.put("key", 2); map3.put("value", 300); list.add(map3); return list; } } ``` 上述代码中,我们通过定义一个Comparator对象,以Map中的键 "key" 进行升序排序。然后,使用Collections.sort方法对List<Map<>>进行排序,并输出排序后的结果。 希望能够帮助到你!如果有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fenghuashao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值