zoukankan      html  css  js  c++  java
  • [一]Head First设计模式之【策略模式】(鸭子设计的优化历程)

    public abstract class Duck {
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;
    public Duck() {
    }
    public abstract void display();
    public void performFly() {
    flyBehavior.fly();
    }
    public void performQuack() {
    quackBehavior.quack();
    }
    public void swim() {
    System.out.println(“All ducks float, even decoys!”);
    }
    public void setFlyBehavior(FlyBehavior fb) {
    flyBehavior = fb;
    }
    public void setQuackBehavior(QuackBehavior qb) {
    quackBehavior = qb;
    }
    
    
    }
    public interface FlyBehavior {
    public void fly();
    }
    public class FlyWithWings implements FlyBehavior {
    public void fly() {
    System.out.println(“I’m flying!!”);
    }
    }
    public class FlyNoWay implements FlyBehavior {
    public void fly() {
    System.out.println(“I can’t fly”);
    }
    }
    public class FlyRocketPowered implements FlyBehavior {
    public void fly() {
    System.out.println(“I’m flying with a rocket!”);
    }
    }
    
    
    
     
    public interface QuackBehavior {
    public void quack();
    }
    public class Quack implements QuackBehavior {
    public void quack() {
    System.out.println(“Quack”);
    }
    }
    public class MuteQuack implements QuackBehavior {
    public void quack() {
    System.out.println(“<< Silence >>”);
    }
    }
    public class Squeak implements QuackBehavior {
    public void quack() {
    System.out.println(“Squeak”);
    }
    }


    public class ModelDuck extends Duck {
    public ModelDuck() {
    flyBehavior = new FlyNoWay();
    quackBehavior = new Quack();
    }
    public void display() {
    System.out.println(“I’m a model duck”);
    }
    }
    
    
    
     
    public class MiniDuckSimulator {
    public static void main(String[] args) {
    Duck mallard = new MallardDuck();
    mallard.performQuack();
    mallard.performFly();
    Duck model = new ModelDuck();
    model.performFly();
    model.setFlyBehavior(new FlyRocketPowered());
    model.performFly();
    
    
    
    
    }
    }

     策略模式:

      定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

  • 相关阅读:
    vs2019 临时下载目录 离线安装 脱机安装
    直膝跳缓解腰椎间盘突出 腰疼 臀部肌肉疼痛
    fullscreen
    ubuntu 18.04 网络图标不见的问题解决方案
    采样率与比特率
    关于git的换行符问题
    在ASP.NET Core中使用EPPlus导入出Excel文件
    .net core 转 excel datatable list<t> 互转 xlsx
    .net core C# DataTable 和List之间相互转换的方法
    C# 的三种序列化方法
  • 原文地址:https://www.cnblogs.com/luoxiaolei/p/5372795.html
Copyright © 2011-2022 走看看