美文网首页
策略模式

策略模式

作者: 樱花舞 | 来源:发表于2019-09-30 17:23 被阅读0次

策略模式:一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。其实简单说就是一个抽象类有多种实现,策略模式在实际中经常用到,比如说购物时选择付款方式,可以支付宝,也可以微信、现金……每个支付方式都是独立的,可以任意替换。

步骤1:创建策略接口:支付方式

public interface Strategy {
    void pay();
}

步骤2:具体策略类:支付宝支付

public class Alipay implements Strategy {
    @Override
    public void pay() {
        System.out.println("支付宝支付");
    }
}

步骤3:具体策略类:微信支付

public class WeChat implements Strategy {
    @Override
    public void pay() {
        System.out.println("微信支付");
    }
}

步骤4:策略环境

public class Context {
    private Strategy strategy;

    public Context() {
    }

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

    public Strategy getStrategy() {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void pay() {
        strategy.pay();
    }
}

使用例子:

public class Test {
    public static void main(String[] args) {
        Context context = new Context(new Alipay());
        context.pay();
    }
}

在实际开发中,单独使用一种模式可能无法更完美解决问题,需要多种模式结合使用。在开发中,我就遇到过这样的场景,一家公司的不同公寓使用了不同厂商的电表,需要把所有的电表统一管理起来,调用一个接口就能根据不同电表进行支付充值。已知电表属于哪个厂商,只需根据厂商类型就可以返回对应的厂商充值对象。如果单独使用策略模式,调用充值前就需要判断电表属于哪个厂商,还需要创建相应的对象,这就比较冗余,如果结合工厂模式,就解决了这样的问题。

1、创建支付接口

public interface Strategy {
    void pay();
}

2、具体实现

A厂商的充值逻辑实现

public class MeterA implements Strategy {
    @Override
    public void pay() {
        System.out.println("厂商A电表充值");
    }
}

B厂商的充值逻辑实现

public class MeterB implements Strategy {
    @Override
    public void pay() {
        System.out.println("厂商B电表充值");
    }
}

3、创建策略工厂

因为在现实中公司不可能使用很多不同的电表厂商,所以根据厂商定一个枚举类。

public enum MeterType {
    METER_A("厂家A"),
    METER_B("厂家B");
    private String type;

    MeterType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
}

创建策略的工厂:

public class StrategyFactory {
    private static StrategyFactory strategyFactory = new StrategyFactory();
    private static Map<String, Strategy> factory = new HashMap<>();

    private StrategyFactory() {
    }

    static {
        factory.put(MeterType.METER_A.getType(), new MeterA());
        factory.put(MeterType.METER_B.getType(), new MeterB());
    }

    /**
     * 返回对应厂商的实现对象
     *
     * @param type
     * @return
     */
    public static Strategy getInstance(String type) {
        return factory.get(type);
    }
}

这种策略工厂模式,如果需要增加一个电表厂商,不需要修改其他逻辑代码,只需实现这个厂商的充值接口,并在工厂中增加对应的厂商类型,完全不影响其他代码逻辑。

相关文章

网友评论

      本文标题:策略模式

      本文链接:https://www.haomeiwen.com/subject/njhhpctx.html