Java 策略模式代替大量 if-else

一、抽象策略类

package com.example.study.strategy;

public interface IColor {

    void describe(ResultCallback callback);

    String argb();

    interface ResultCallback {
        void result(String msg);
    }

}

二、具体策略类

package com.example.study.strategy;

public class Blue implements IColor {
    @Override
    public void describe(ResultCallback callback) {
        callback.result("0xFF0000FF");
        System.out.println("this is blue");
    }

    @Override
    public String argb() {
        return "blue";
    }
}

package com.example.study.strategy;

public class Red implements IColor {
    @Override
    public void describe(ResultCallback callback) {
        callback.result("0xFFFF0000");
        System.out.println("this is red");
    }

    @Override
    public String argb() {
        return "red";
    }
}

package com.example.study.strategy;

public class Yellow implements IColor {
    @Override
    public void describe(ResultCallback callback) {
        callback.result("0xFFFFFF00");
        System.out.println("this is yellow");
    }

    @Override
    public String argb() {
        return "yellow";
    }
}

三、策略Context,获取具体策略实例

package com.example.study.strategy;

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

public class ColorContext {

    private IColor color;

    private static Map<String, String> map = new HashMap<String, String>() {{
        put("blue", "com.example.study.strategy.Blue");
        put("red", "com.example.study.strategy.Red");
        put("yellow", "com.example.study.strategy.Yellow");
    }};


    // 如果单独用这个方法,可以理解是简单工厂模式
    private static IColor getColor(String type) {
        IColor color = null;
        try {
            try {
                color = (IColor) Class.forName(map.get(type)).newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return color;
    }

    public void setColor(String type) {
        this.color = getColor(type);
    }

    public void describe(IColor.ResultCallback callback) {
        this.color.describe(callback);
    }

    public String argb() {
        return this.color.argb();
    }
}

四、测试调用

package com.example.study;

import com.example.study.strategy.ColorContext;

public class MyClass {

    public static void main(String[] args) {

        ColorContext context = new ColorContext();
        context.setColor("red");
        context.describe(System.out::println);
        context.setColor("yellow");
        System.out.println(context.argb());

    }

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值