java设计模式之策略模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010739551/article/details/89840147

一、定义算法族和实现

public interface IAttack {

    public void attack();

}
public interface IDisplay {

    public void display();

}
public interface IRun {

    public void run();

}
public class AoeAttack implements IAttack {

    @Override
    public void attack() {
        System.out.println("AOE伤害");
    }

}
public class SingleAttack implements IAttack {

    @Override
    public void attack() {
        System.out.println("单体伤害");
    }

}
public class GoodDisplay implements IDisplay {

    @Override
    public void display() {
        System.out.println("长得好看");
    }
}
public class BadDisplay implements IDisplay {

    @Override
    public void display() {
        System.out.println("长得难看");
    }
}
public class FastRun implements IRun {

    @Override
    public void run() {
        System.out.println("跑得快");
    }
}
public class SlowRun implements IRun {

    @Override
    public void run() {
        System.out.println("跑得慢");
    }
}

二、定义使用算法的客户(抽象类和基础类)

public abstract class Role {

    protected String name;

    private IDisplay display;

    private IAttack attack;

    private IRun run;

    public void setDisplay(IDisplay display) {
        this.display = display;
    }

    public void setAttack(IAttack attack) {
        this.attack = attack;
    }

    public void setRun(IRun run) {
        this.run = run;
    }

    public void display(){
        this.display.display();
    }

    public void attack(){
        this.attack.attack();
    }

    public void run(){
        this.run.run();
    }

}
public class CikeRole extends Role {

    public CikeRole(String name){
        this.name = name;
    }

}
public class FashiRole extends Role {

    public FashiRole(String name){
        this.name = name;
    }

}

三、测试结果

参考:https://blog.csdn.net/u010739551/article/details/44788619

 

展开阅读全文

没有更多推荐了,返回首页