zoukankan      html  css  js  c++  java
  • 用最简单的例子理解策略模式(Strategy Pattern)

    当一个动作有多种实现方法,在实际使用时,需要根据不同情况选择某个方法执行动作,就可以考虑使用策略模式。

     

    把动作抽象成接口,比如把玩球抽象成接口。

        public interface IBall
    
        {
    
            void Play();
    
        }

    有可能是玩足球、篮球、排球等,把这些球类抽象成实现接口的类。

        public class Football : IBall
    
        {
    
            public void Play()
    
            {
    
                Console.WriteLine("我喜欢足球");
    
            }
    
        }
    
        public class Basketball : IBall
    
        {
    
            public void Play()
    
            {
    
                Console.WriteLine("我喜欢篮球");
    
            }
    
        }
    
        public class Volleyball : IBall
    
        {
    
            public void Play()
    
            {
    
                Console.WriteLine("我喜欢排球");
    
            }
    
        }   
    

    还有一个类专门用来选择哪种球类,并执行接口方法。

        public class SportsMan
    
        {
    
            private IBall ball;
    
            public void SetHobby(IBall myBall)
    
            {
    
                ball = myBall;
    
            }
    
            public void StartPlay()
    
            {
    
                ball.Play();
    
            }
    
        }
    

    客户端需要让用户作出选择,根据不同的选择实例化具体类。

        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                IBall ball = null;
    
                SportsMan man = new SportsMan();
    
                while (true)
    
                {
    
                    Console.WriteLine("选择你喜欢的球类项目(1=足球, 2=篮球,3=排球)");
    
                    string input = Console.ReadLine();
    
                    switch (input)
    
                    {
    
                        case "1":
    
                            ball = new Football();
    
                            break;
    
                        case "2":
    
                            ball = new Basketball();
    
                            break;
    
                        case "3":
    
                            ball = new Volleyball();
    
                            break;
    
                    }
    
                    man.SetHobby(ball);
    
                    man.StartPlay();
    
                }
    
            }
    
        }
    

    1

  • 相关阅读:
    停下来,等等灵魂(二)
    停下来,等等灵魂(一)
    swoole流程图
    使用 Spring Cloud Sleuth、Elastic Stack 和 Zipkin 做微服务监控
    Portainer实战
    Docker 容器日志分析
    docker容器日志查看
    java(集合框架)(转)
    js中const,var,let区别与用法(转)
    【MySQL】Mac通过brew安装的MySQL重启方法
  • 原文地址:https://www.cnblogs.com/darrenji/p/3959904.html
Copyright © 2011-2022 走看看