首页 > 其他分享 >CSharp: Strategy Pattern in donet core 3

CSharp: Strategy Pattern in donet core 3

时间:2022-10-08 23:46:07浏览次数:67  
标签:core Name Person Pattern Age Strategy public 排序 Id

 

  /// <summary>
    /// 车辆行为模型
    /// Abstract Behavior
    /// 策略模式 Strategy Pattern 
    /// geovindu, Geovin Du edit
    /// 
    /// </summary>
    public abstract class VehicleBehavior
    {

        /// <summary>
        /// 关于我
        /// </summary>
        /// <param name="vehicle">输入车名称</param>
        public abstract void AboutMe(string vehicle);
    }
    /// <summary>
    /// Floating capability
    /// 移动的能力
    /// </summary>
    class FloatBehavior : VehicleBehavior
    {

        /// <summary>
        /// 关于我
        /// </summary>
        /// <param name="vehicle">输入车名称</param>
        public override void AboutMe(string vehicle)
        {
            Console.WriteLine($"我的 {vehicle} 现在能移动.");
        }
    }
    /// <summary>
    /// Flying capability
    /// 飞行能力
    /// </summary>
    class FlyBehavior : VehicleBehavior
    {
        /// <summary>
        /// 关于我
        /// </summary>
        /// <param name="vehicle">输入车名称</param>
        public override void AboutMe(string vehicle)
        {
            Console.WriteLine($"我的 {vehicle} 现在能飞.");
        }
    }
    /// <summary>
    /// Initial behavior.Cannot do anything special.
    /// </summary>
    class InitialBehavior : VehicleBehavior
    {
        /// <summary>
        /// 关于我
        /// </summary>
        /// <param name="vehicle">输入车名称</param>
        public override void AboutMe(string vehicle)
        {
            Console.WriteLine($"我的 {vehicle} 刚产生.它不能做特别的事情.");
        }
    }
    /// <summary>
    /// Context class-Vehicle
    /// 车对象类
    /// </summary>
    public class Vehicle
    {
        /// <summary>
        /// 
        /// </summary>
        VehicleBehavior behavior;
        /// <summary>
        /// 类型
        /// </summary>
        string vehicleType;

        /// <summary>
        /// 构造对象
        /// </summary>
        /// <param name="vehicleType">输入类型</param>
        public Vehicle(string vehicleType)
        {
            this.vehicleType = vehicleType;
            //Setting the initial behavior
            this.behavior = new InitialBehavior();
        }
        /*
         * It's your choice. You may prefer to use a setter
         * method instead of using a constructor. 
         * You can call this method whenever we want
         * to change the "vehicle behavior" on the fly.
         */
        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="behavior"></param>
        public void SetVehicleBehavior(VehicleBehavior behavior)
        {
            this.behavior = behavior;
        }
        /* 
         This method will help us to delegate the behavior to
         the object referenced by vehicle.You do not know about
         the object type, but you simply know that this object can
         tell something about it, i.e. "AboutMe()" method
        */
        /// <summary>
        /// 显示
        /// </summary>
        public void DisplayAboutMe()
        {
            behavior.AboutMe(vehicleType);
        }
    }

  

   /// <summary>
    /// 策略模式 Strategy Pattern 
    /// geovindu, Geovin Du edit
    /// </summary>
    public enum OutputFormat
    {
        Markdown,
        Html
    }
    /// <summary>
    /// 
    /// </summary>
    public interface IListStrategy
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        void Start(StringBuilder sb);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        void End(StringBuilder sb);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="item"></param>
        void AddListItem(StringBuilder sb, string item);
    }
    /// <summary>
    /// 
    /// </summary>
    public class MarkdownListStrategy : IListStrategy
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        public void Start(StringBuilder sb)
        {
            // markdown doesn't require a list preamble
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        public void End(StringBuilder sb)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="item"></param>
        public void AddListItem(StringBuilder sb, string item)
        {
            sb.AppendLine($" * {item}");
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class HtmlListStrategy : IListStrategy
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        public void Start(StringBuilder sb) => sb.AppendLine("<ul>");
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        public void End(StringBuilder sb) => sb.AppendLine("</ul>");
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="item"></param>
        public void AddListItem(StringBuilder sb, string item)
        {
            sb.AppendLine($"  <li>{item}</li>");
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class TextProcessor
    {
        /// <summary>
        /// 
        /// </summary>
        private StringBuilder sb = new StringBuilder();
        /// <summary>
        /// 
        /// </summary>
        private IListStrategy listStrategy;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="format"></param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public void SetOutputFormat(OutputFormat format)
        {
            switch (format)
            {
                case OutputFormat.Markdown:
                    listStrategy = new MarkdownListStrategy();
                    break;
                case OutputFormat.Html:
                    listStrategy = new HtmlListStrategy();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(format), format, null);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="items"></param>
        public void AppendList(IEnumerable<string> items)
        {
            listStrategy.Start(sb);
            foreach (var item in items)
                listStrategy.AddListItem(sb, item);
            listStrategy.End(sb);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public StringBuilder Clear()
        {
            return sb.Clear();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString() => sb.ToString();


    }

  

  /// <summary>
    /// 策略模式 Strategy Pattern 
    /// geovindu, Geovin Du edit
    /// </summary>
    class Person : IEquatable<Person>, IComparable<Person>
    {
        /// <summary>
        /// 
        /// </summary>
        public int Id;
        /// <summary>
        /// 
        /// </summary>
        public string Name;
        /// <summary>
        /// 
        /// </summary>
        public int Age;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public int CompareTo(Person other)
        {
            if (ReferenceEquals(this, other)) return 0;
            if (ReferenceEquals(null, other)) return 1;
            return Id.CompareTo(other.Id);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="age"></param>
        public Person(int id, string name, int age)
        {
            Id = id;
            Name = name;
            Age = age;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public bool Equals(Person other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Id == other.Id;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((Person)obj);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return Id;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return $"序号({nameof(Id)}):{Id};姓名({nameof(Name)}):{Name};年岁({nameof(Age)}):{Age}";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static bool operator ==(Person left, Person right)
        {
            return Equals(left, right);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static bool operator !=(Person left, Person right)
        {
            return !Equals(left, right);
        }
        /// <summary>
        /// 
        /// </summary>
        private sealed class NameRelationalComparer : IComparer<Person>
        {

            /// <summary>
            /// 
            /// </summary>
            /// <param name="x"></param>
            /// <param name="y"></param>
            /// <returns></returns>
            public int Compare(Person x, Person y)
            {
                if (ReferenceEquals(x, y)) return 0;
                if (ReferenceEquals(null, y)) return 1;
                if (ReferenceEquals(null, x)) return -1;
                return string.Compare(x.Name, y.Name,
                  StringComparison.Ordinal);
            }
        }

        /// <summary>
        /// 名字排序
        /// </summary>
        public static IComparer<Person> NameComparer { get; }
          = new NameRelationalComparer();
    }

  

调用:

        //策略模式
            Console.WriteLine("***策略模式 Strategy Pattern Demo.***\n");
            Vehicle context = new Vehicle("Aeroplane(飞机)");
            context.DisplayAboutMe();
            Console.WriteLine("Setting  flying capability(设置飞行能力) to vehicle.");
            context.SetVehicleBehavior(new FlyBehavior());
            context.DisplayAboutMe();
           
            Console.WriteLine("Changing the vehicle behavior(改为移动能力) again.");
            context.SetVehicleBehavior(new FloatBehavior());
            context.DisplayAboutMe();

            //
            var tp = new TextProcessor();
            tp.SetOutputFormat(OutputFormat.Markdown);
            tp.AppendList(new[] { "foo", "bar", "baz" });
            Console.WriteLine(tp);

            tp.Clear();
            tp.SetOutputFormat(OutputFormat.Html);
            tp.AppendList(new[] { "foo", "bar", "baz" });
            Console.WriteLine(tp);

            //
            var people = new List<Person>();

            // equality == != and comparison < = >

            people.Add(new Person(1, "geovindu", 25));
            people.Add(new Person(2, "涂聚文", 28));
            people.Add(new Person(3, "江山", 38));
            people.Add(new Person(4, "李玉", 18));
            people.Add(new Person(5, "张清", 20));
            people.Sort(); // meaningless by default
            foreach (Person p in people)
            {
                Console.WriteLine("第1次ID排序:" + p.ToString());
            }
            Console.WriteLine("***.***\n");
            // sort by name with a lambda
            //名字排序
            people.Sort((x, y) => x.Name.CompareTo(y.Name));

            foreach (Person p in people)
            {
                Console.WriteLine("第2次名字排序:" + p.ToString());
            }
            Console.WriteLine("***.***\n");
            //
            people.Sort(Person.NameComparer);

            foreach(Person p in people)
            {
                Console.WriteLine("第3次名字排序"+p.ToString());
            }
            Console.WriteLine("***.***\n");
            people.Sort((x, y) => x.Age.CompareTo(y.Age));

            foreach (Person p in people)
            {
                Console.WriteLine("第4次年龄排序" + p.ToString());
            }


            Console.ReadKey();
        }

  

输出:

***策略模式 Strategy Pattern Demo.***

我的 Aeroplane(飞机) 刚产生.它不能做特别的事情.
Setting  flying capability(设置飞行能力) to vehicle.
我的 Aeroplane(飞机) 现在能飞.
Changing the vehicle behavior(改为移动能力) again.
我的 Aeroplane(飞机) 现在能移动.
 * foo
 * bar
 * baz

<ul>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

第1次ID排序:序号(Id):1;姓名(Name):geovindu;年岁(Age):25
第1次ID排序:序号(Id):2;姓名(Name):涂聚文;年岁(Age):28
第1次ID排序:序号(Id):3;姓名(Name):江山;年岁(Age):38
第1次ID排序:序号(Id):4;姓名(Name):李玉;年岁(Age):18
第1次ID排序:序号(Id):5;姓名(Name):张清;年岁(Age):20
***.***

第2次名字排序:序号(Id):1;姓名(Name):geovindu;年岁(Age):25
第2次名字排序:序号(Id):3;姓名(Name):江山;年岁(Age):38
第2次名字排序:序号(Id):4;姓名(Name):李玉;年岁(Age):18
第2次名字排序:序号(Id):2;姓名(Name):涂聚文;年岁(Age):28
第2次名字排序:序号(Id):5;姓名(Name):张清;年岁(Age):20
***.***

第3次名字排序序号(Id):1;姓名(Name):geovindu;年岁(Age):25
第3次名字排序序号(Id):5;姓名(Name):张清;年岁(Age):20
第3次名字排序序号(Id):4;姓名(Name):李玉;年岁(Age):18
第3次名字排序序号(Id):3;姓名(Name):江山;年岁(Age):38
第3次名字排序序号(Id):2;姓名(Name):涂聚文;年岁(Age):28
***.***

第4次年龄排序序号(Id):4;姓名(Name):李玉;年岁(Age):18
第4次年龄排序序号(Id):5;姓名(Name):张清;年岁(Age):20
第4次年龄排序序号(Id):1;姓名(Name):geovindu;年岁(Age):25
第4次年龄排序序号(Id):2;姓名(Name):涂聚文;年岁(Age):28
第4次年龄排序序号(Id):3;姓名(Name):江山;年岁(Age):38

  

标签:core,Name,Person,Pattern,Age,Strategy,public,排序,Id
From: https://www.cnblogs.com/geovindu/p/16770698.html

相关文章

  • CSharp: Observer Pattern in donet core 3
     ///<summary>///观察者模式ObserverPattern亦称:事件订阅者、监听者、Event-Subscriber、Listener、Observe///geovindu,GeovinDueidt///......
  • 使用EF Core更新与修改生产数据库
    使用EFCore的CodeFirst,在设计阶段,直接使用Database.EnsureCreated()和EnsureDeleted()可以快速删除、更新最新的数据结构。由于没有什么数据,删除的风险非常低。但是对于......
  • .NET Core和.NET Framework中DateTime.Now的区别
    今天和医院的微信公众号接口对接,需要传当前时间,我随手写了一个DateTime.Now传了过去,过了一会那边说时间格式不对,原来.NETCore中DateTime.Now的格式是2022/10/08下午04......
  • CentOS7安装.netCore
    CentOS7安装.NET之前,请运行以下命令,将Microsoft包签名密钥添加到受信任密钥列表,并添加Microsoft包存储库。打开终端并运行以下命令:sudorpm-Uvhhttps://packa......
  • Asp.Net Core Request生命周期
    官网文档有这么个图:返回的时候为什么还又反向走了各个MiddleWare的逻辑呢?所以按它这个图里的代码组织方式试了一下。图里的四个exeorder还真是以'next()'为为界,把一......
  • NETCORE - ElasticSearch 搜索服务
                                            引用:https://www.cnblogs.com/qiect/arti......
  • DotnetCore3.1出现Method ‘Create‘ in type ... does not have an implementation
    错误提示如下:出现这个问题的原因是安装的Microsoft.EntityFrameworkCore.Design包版本是5.0.17,而它所依赖的其他包版本是3.1.25,解决方案就是将Microsoft.EntityFramework......
  • .NET Core短信验证
      思路: 1、构造手机验证码,需要生成一个6位的随机数字串; 2、找短信平台获取使用接口向短信平台发送手机号和验证码,然后短信平台再把验证码发送到制定手机号上 3......
  • 搭建Swagger框架时,浏览不到Swashbuckle.AspNetCore包的简单解决办法
    什么是Swagger?Swagger是一款RESTFUL接口的文档在线自动生成+功能测试的软件。Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTFUL风格的Web服务。 ......
  • ASP.NETCore中REST落地指南
    1、控制器上[Route("[controller]/[action]")]2、强制要求控制器中不同的操作用不同的方法名3、把[HttpGet]、[HttpPost]、[HttpDelete]、[HttpPut]等添加到对应的操作方法......