首页 > 其他分享 >策略模式

策略模式

时间:2023-06-03 21:33:06浏览次数:31  
标签:IStrategy 策略 class When 模式 strategy Strategy public

The Strategy design pattern defines a familiy of algorithms, encapsulate each one, and make them interchangeable. This pattern lets the algorithm vary independently from client that use it.

策略模式定义一系列算法,封装它,使他们可以互换,这种设计模式使算法独立于客户端的使用。

The Strategy Design Pattern is used when we have multiple algorighms(solutions) for a specific task and the client decides on the actual implementation to be used at runtime. In simple words, we can say that the Strategy Design Pattern (also called Policy Pattern) attempts to solve the issue when you need to provide multiple solutions for the same problem so that one can be selected at runtime.

UML Class Diagram

 Strategy: declares an interface common to all supported algorithms.Context uses this interface to call the algorithm defined by a ConcreteStrategy.

 ConcreteStrategy: There are going to be concrete classes and they must implement the Strategy interface and provide implementations for the algorighm.

 Context: This is going to be a class that maitains a reference to a Strategy object, and then uses that reference to call the algorithm defined by a particular ConcreteStrategy.

Structure Code IN C#

ublic interface IStrategy
    {
        void AlgorithmInterface();
    }

    public class ConcreteStrategyA : IStrategy
    {
        public void AlgorithmInterface()
        {
            Console.WriteLine($"{typeof(ConcreteStrategyA).Name} action.");
        }
    }

    public class ConcreteStrategyB : IStrategy
    {
        public void AlgorithmInterface()
        {
            Console.WriteLine($"{typeof(ConcreteStrategyB).Name} action.");
        }
    }
Strategy
public class StrategyContext
    {
        private IStrategy? _strategy;
        public StrategyContext()
        {
        }
        public StrategyContext(IStrategy strategy ) 
        {
            this._strategy = strategy;
        }
        public void SetStrategy(IStrategy strategy ) 
        {
            this._strategy = strategy;
        }

        public void ContextInterface()
        {
            _strategy?.AlgorithmInterface();
        }
    }
Context
var context = new StrategyContext();
context.SetStrategy(new ConcreteStrategyA());
context.ContextInterface();
context.SetStrategy(new ConcreteStrategyB());
context.ContextInterface();
Client

When do we need to use the Strategy Design Pattern in Real-Time Applications?

  • When there are multiple solutions for a given task and the selection criteria of a solution are defined at run-time.
  • When you want different variants of an algorithm
  • When many related classes differ only in their behavior.
  • When a class defines many behaviors and these appear as multiple conditional statements in tis operations. Instead of many conditonal statements, move-related conditonal branches into their own strategy class.
  • When an algorithm uses data that the client shouldn't know about. Use the Strategy Design Pattern to avoid exposing complex and algorithm-specific data structures.

 

标签:IStrategy,策略,class,When,模式,strategy,Strategy,public
From: https://www.cnblogs.com/qindy/p/17430910.html

相关文章

  • 3月25日邓老师设计模式面试资料02
    Spring面试专题1.Spring应该很熟悉吧?来介绍下你的Spring的理解  有些同学可能会抢答,不熟悉!!!  好了,不开玩笑,面对这个问题我们应该怎么来回答呢?我们给大家梳理这个几个维度来回答1.1Spring的发展历程  先介绍Spring是怎么来的,发展中有哪些核心的节点,当前的最新版本是......
  • 大话设计模式之单例,策略,简单工厂
    基于实际面试题实现importjava.util.HashMap;importjava.util.Map;importjava.util.Random;/***用java设计一个机房环境监测系统的代码框架,机房有多种传感器,可以实时检测机房的温度、湿度、噪音等数据,*并把数据实时发送到监控中心,其中某项数据超过不健康阈值立即上......
  • 树莓派如果通过 raspi-config 关闭桌面模式 All In One
    树莓派如果通过raspi-config关闭桌面模式AllInOne树莓派设置启动模式:切换桌面模式和命令行模式DesktopCommandLineGUIvsCLI图形化界面vs命令行$sudoraspi-config$sudovim/boot/config.txt$sudoreboot$sudoshutdwon-hnowautologinde......
  • 大白话讲解数据库的三级模式(所谓的内外模式在生活中到底是什么东西?)
    具象化理解数据库的三级模式形象一点来说,把数据看做货物,数据库是仓库,模式就是表格。你有一个仓库,仓库里成千上万的货物,随便你怎么堆,你堆个正方体,堆个圆柱体,甚至随便乱堆都行,你怎么堆的叫内模式。完事你写了一张表,表上对全部货物按某个标准分类,而且标清了啥货物在哪(这个是模式内......
  • Java开发 - 让你少走弯路的Redis主从实现单节点哨兵模式
    前言前一篇中,我们讲解了Redis主从的搭建方式,其实很简单呐有木有,都是配置,连句代码都没有,是不是感觉高估了Redis主从的搭建方式?哈哈,没关系,跟着博主,包你全会。今天我们的主题是哨兵,没错,就是哨兵!有了Redis,要是没有哨兵,那真是太可惜了,哨兵是很神圣的一种重要的监测工具,有了哨兵,在Redis主......
  • 单例模式8种写法
    0.为什么需要单例模式?节省内存和计算保证结果正确方便管理使用场景:1.饿汉式(静态常量)—推荐指数:★★☆☆☆优点:不会有线程安全问题。缺点:在类加载的时候就创建对象,如果一直没使用到该对象的话,就造成了内存浪费,如果对象初始化的工作有很多,也会影响到性能。代码展示://......
  • 单例模式的运用
    目录一、介绍二、饿汉式2.1静态变量方式2.2静态代码块方式2.3枚举方式三、懒汉式3.1线程不安全方式3.2线程安全方式3.3双重检查锁方式3.4静态内部类方式四、破坏单例模式4.1序列化破坏4.2序列化破坏解决办法4.3反射破坏4.4反射破坏解决办法一、介绍单例模式:属于创建......
  • android-夜间模式
    资源1AndroidMaterialDesign系列之夜间模式阐述了夜间模式的资源文件,告知建立了values-night文件夹对于夜间模式的颜色和主题配置,我们需要建立一个res下建立一个values-night文件夹,里面放着夜间主题样式的color等资源。colors.xml配置如下:<?xmlversion="1.0"encoding="utf-8"......
  • 移动开发之设计模式-组合模式(IOS&Android)
    组合模式组合模式(CompositePattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。这种模式创建了一个包含自己对象组的类。该类提供了修改相......
  • java单例模式几种实现方式
    1、饿汉式(线程安全,调用效率高,但是不能延时加载):publicclassImageLoader{privatestaticImageLoaderinstance=newImageLoader;privateImageLoader(){}publicstaticImageLoadergetInstance(){returninstance;}}一上来就把单例对象创建出来了,要用的时候直......