策略模式

策略模式

package com.bigdata.strategy.v2;

/**
 * Copyright (c) 2019 leyou ALL Rights Reserved Project: learning Package: com.bigdata.strategy.v2
 * Version: 1.0
 *
 * @author qingzhi.wu
 * @date 2020/6/18 14:01
 */
public class StrategyV2Test {
  public static void main(String[] args) {
    Zombie zombie = new NormalZombie();
    zombie.display();
    zombie.attack();
    zombie.move();


    Zombie flag = new FlagZombie();
    flag.display();
    flag.attack();
    flag.move();
    flag.setAttackable(new HitAttack());

    flag.attack();
  }
}

interface Moveable {
  void move();
}

interface Attackable {
  void attack();
}

abstract class Zombie {
  public abstract void display();

  Moveable moveable;
  Attackable attackable;

  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 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();
  }
}

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 BiteAttack implements Attackable {

  @Override
  public void attack() {
    System.out.println("咬");
  }
}

class StepByStepMove implements Moveable {

  @Override
  public void move() {
    System.out.println("一步一步移动.");
  }
}

class HitAttack implements Attackable {

    @Override
    public void attack() {
        System.out.println("打");
    }
}

你可能感兴趣的:(设计模式)