Java中策略模式_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java中策略模式

Java中策略模式

 2018/10/16 15:45:25  andrew7676  程序员俱乐部  我要评论(0)
  • 摘要:1.Java中策略模式publicinterfaceStrategy{publicintcalculate(inta,intb);}publicclassAddStrategyimplementsStrategy{publicintcalculate(inta,intb){returna+b;}}publicclassDivideStrategyimplementsStrategy{publicintcalculate(inta,intb){returna/b;}
  • 标签:Java 模式
1. Java中策略模式
class="(抽象策略角色)接口">
public interface Strategy{
    public int calculate(int a, int b);
}

public class AddStrategy implements Strategy{
    public int calculate(int a, int b){
        return a + b;
    }
}

public class DivideStrategy implements Strategy{
    public int calculate(int a, int b){
        return a / b;
    }
}

public class MultiplyStrategy implements Strategy{
    public int calculate(int a, int b){
        return a * b;
    }
}

public class SubtractStrategy implements Strategy{
    public int calculate(int a, int b){
        return a - b;
    }
}

public class Environment{
    private Strategy strategy;
    public Environment(Strategy strategy){
        this.strategy = strategy;
    }
    public Strategy getStrategy(){
        return strategy;
    }
    public void setStrategy(Strategy strategy){
        this.strategy = strategy;
    }
    public int calculate(int a ,int b){
        return strategy.calculate(a , b);
    }
}

public class Client{
    public static void main(String[] args){
        AddStrategy addStrategy = new AddStrategy();
        Environment environment = new Environment(addStrategy);
        System.out.println(environment.calculate(3, 4));
        SubtractStrategy subtractStrategy = new SubtractStrategy();
        environment.setStrategy(subtractStrategy);
        System.out.println(environment.calculate(3, 4));
        MultiplyStrategy multiplyStrategy = new MultiplyStrategy();
        environment.setStrategy(multiplyStrategy);
        System.out.println(environment.calculate(3, 4));
        DivideStrategy divideStrategy = new DivideStrategy();
        environment.setStrategy(divideStrategy);
        System.out.println(environment.calculate(3, 4));
    }
}
上一篇: Java中代理模式 下一篇: 没有下一篇了!
发表评论
用户名: 匿名