• 策略模式


    Context:使用不同的策略的环境,它可以根据自身的条件选择不同的策略实现类来完成所要的操作。它持有一个策略实例的引用,创建具有策略对象的方法也可以由它完成

    Strategy:抽象策略,定义每个策略都要实现的策略方法

    Strategy

    package design.pattern.strategy;
    
    public interface Strategy {
        public void run();
    }

    ConcreteStrateA

    package design.pattern.strategy;
    
    public class ConcreteStrateA implements Strategy{
    
        @Override
        public void run() {
            System.out.println("ConcreteStrateA");
        }
    
    }

    ConcreteStrateB

    package design.pattern.strategy;
    
    public class ConcreteStrateB implements Strategy{
    
        @Override
        public void run() {
            System.out.println("ConcreteStrateB");
        }
    
    }

    Context

    package design.pattern.strategy;
    
    public class Context {
        private Strategy strategy;
        
        public Context(Strategy strategy) {
            this.strategy = strategy;
        }
        
        public void setStrategy(Strategy strategy) {
            this.strategy = strategy;
        }
        
        public void run() {
            strategy.run();
        }
    }

    Client

    package design.pattern.strategy;
    
    public class Client {
        public static void main(String[] args) {
            Context context = new Context(new ConcreteStrateA());
            context.run();
            context.setStrategy(new ConcreteStrateB());
            context.run();
        }
    }
  • 相关阅读:
    delphi安装pngimage控件,不需要安装,只需引用就行
    怎样把PL/SQLDeveloper字体调大
    resource is out of sync with the file
    SecureCRT:[1]SecureCRT配色方案
    安装开发环境注意事项2
    插入排序
    tomcat更改端口序
    tomcat更改端口
    maven添加jar包
    java总结
  • 原文地址:https://www.cnblogs.com/m2492565210/p/7245569.html
Copyright © 2020-2023  润新知