策略模式(Strategy)
1 概念
- 定义了算法族,分别封装起来,让它们之间可以互相替换,此模式的变化独立于算法的使用者。
2 实现
package com.xianhuii.designpattern;
public class Strategy {
public static void main(String[] args) {
NormalZombie normalZombie = new NormalZombie();
normalZombie.display();
normalZombie.attack();
normalZombie.move();
normalZombie.setAttackable(new HitAttack());
normalZombie.attack();
}
}
interface Moveable {
void move();
}
interface Attackable {
void attack();
}
abstract class Zombie {
abstract public void display();
Moveable moveable;
Attackable attackable;
public Zombie(){}
public Zombie(Moveable moveable, Attackable attackable) {
this.moveable = moveable;
this.attackable = attackable;
}
abstract void move();
abstract void attack();
public Moveable getMoveable() {
return moveable;
}
public void setMoveable(Moveable moveable) {
this.moveable = moveable;
}
public Attackable getAttackable() {
return attackable;
}
public void setAttackable(Attackable attackable) {
this.attackable = attackable;
}
}
class StepByStepMove implements Moveable {
@Override
public void move() {
System.out.println("一步一步移动");
}
}
class BiteAttack implements Attackable {
@Override
public void attack() {
System.out.println("咬");
}
}
class HitAttack implements Attackable {
@Override
public void attack() {
System.out.println("打");
}
}
class NormalZombie extends Zombie {
public NormalZombie() {
super(new StepByStepMove(), new BiteAttack());
}
public NormalZombie(Moveable moveable, Attackable attackable) {
super(moveable, attackable);
}
@Override
public void display() {
System.out.println("普通僵尸");
}
@Override
void move() {
moveable.move();
}
@Override
void attack() {
attackable.attack();
}
}
class FlagZombie extends Zombie {
public FlagZombie() {
super(new StepByStepMove(), new BiteAttack());
}
public FlagZombie(Moveable moveable, Attackable attackable) {
super(moveable, attackable);
}
@Override
public void display() {
System.out.println("旗手僵尸");
}
@Override
void move() {
moveable.move();
}
@Override
void attack() {
attackable.attack();
}
} 
京公网安备 11010502036488号