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

CSharp: Facade Pattern in donet core 3

时间:2022-10-05 23:44:05浏览次数:53  
标签:core Console Pattern robot var Facade new array public

 

  /// <summary>
    /// 外观模式Facade Pattern
    /// geovindu,Geovin Du eidt
    /// 机器人颜色
    /// </summary>
    public class RobotColor
    {

        /// <summary>
        /// 颜色名称
        /// </summary>
        string color;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="color"></param>
        public RobotColor(string color)
        {
            this.color = color;
        }
        /// <summary>
        /// 设置颜色
        /// </summary>
        public void SetColor()
        {
            if (color == "steel")
            {
                Console.WriteLine($"The default color {color} is set for the robot.");
            }
            else
            {
                Console.WriteLine($"Painting the robot with your favourite {color} color.");
            }
        }
        /// <summary>
        /// 移除颜色
        /// </summary>
        public void RemoveColor()
        {
            Console.WriteLine("Attempting to remove the colors from the robot.");
        }
    }

  

   /// <summary>
    /// 外观模式Facade Pattern
    /// geovindu,Geovin Du eidt
    /// 机器人身体
    /// </summary>
    class RobotBody
    {
        /// <summary>
        /// 类型
        /// </summary>
        string robotType;
        /*
        * To keep a count of number of robots.
        * This operation is optional for you.
       */
        /// <summary>
        /// 数量
        /// </summary>
        static int count = 0;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="robotType">输入类型名称</param>
        public RobotBody(string robotType)
        {
            this.robotType = robotType;
        }

        /// <summary>
        /// 制造机器人身体
        /// </summary>
        public void MakeRobotBody()
        {
          Console.WriteLine($"Constructing one {robotType} robot.");
          Console.WriteLine("Robot creation finished.");
          Console.WriteLine($"Total number of robot created at this moment:(目前机器人总数为){++count}");  //制造一个,数量上加一
        }
        /// <summary>
        /// 破坏机器人身体
        /// </summary>
        public void DestroyRobotBody()
        {
            if (count > 0)
            {
                --count; //破坏一个,数量减一
                Console.WriteLine($"Robot's destruction process is over.剩余总数为:{count}");
            }
            else
            {
                Console.WriteLine("All robots are destroyed already.所有都已经损坏,没有可以做的。");
                Console.WriteLine("Color removal operation will not continue.");
            }
        }
    }

  

   /// <summary>
    /// 外观模式Facade Pattern
    /// geovindu,Geovin Du eidt
    /// 
    /// </summary>
    class RobotFacade
    {
        RobotBody robotBody;
        RobotColor robotColor;    
        
        /// <summary>
        /// 构造一个类
        /// </summary>
        /// <param name="robotType">输入类型名称</param>
        /// <param name="color">输入设置颜色</param>
        public RobotFacade(string robotType, string color = "steel")
        {
            robotBody = new RobotBody(robotType);
            robotColor = new RobotColor(color);
        }
        /// <summary>
        /// 创建一个机器人方法
        /// </summary>
        public void ConstructRobot()
        {
            Console.WriteLine("Robot creation through facade starts...(造造一个)");

            robotBody.MakeRobotBody();
            
            robotColor.SetColor();

            Console.WriteLine();
        }
        /// <summary>
        /// 损坏一个机器人方法
        /// </summary>
        public void DestroyRobot()
        {
            Console.WriteLine("Making an attempt to destroy one robot using the facade now.(损坏一个)");

            robotColor.RemoveColor();

            robotBody.DestroyRobotBody();

            Console.WriteLine();
        }
    }

  

  /// <summary>
    /// 外观模式Facade Pattern
    /// geovindu,Geovin Du eidt
    /// </summary>
    public class Generator
    {
        private static readonly Random random = new Random();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="count">3</param>
        /// <returns></returns>
        public List<int> Generate(int count)
        {
            return Enumerable.Range(0, count)
              .Select(_ => random.Next(1, 6))
              .ToList();
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class Splitter
    {
        public List<List<int>> Split(List<List<int>> array)
        {
            var result = new List<List<int>>();

            var rowCount = array.Count;
            var colCount = array[0].Count;

            // get the rows
            for (int r = 0; r < rowCount; ++r)
            {
                var theRow = new List<int>();
                for (int c = 0; c < colCount; ++c)
                    theRow.Add(array[r][c]);
                result.Add(theRow);
            }

            // get the columns
            for (int c = 0; c < colCount; ++c)
            {
                var theCol = new List<int>();
                for (int r = 0; r < rowCount; ++r)
                    theCol.Add(array[r][c]);
                result.Add(theCol);
            }

            // now the diagonals
            var diag1 = new List<int>();
            var diag2 = new List<int>();
            for (int c = 0; c < colCount; ++c)
            {
                for (int r = 0; r < rowCount; ++r)
                {
                    if (c == r)
                        diag1.Add(array[r][c]);
                    var r2 = rowCount - r - 1;
                    if (c == r2)
                        diag2.Add(array[r][c]);
                }
            }

            result.Add(diag1);
            result.Add(diag2);

            return result;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class Verifier
    {
        public bool Verify(List<List<int>> array)
        {
            if (!array.Any()) return false;

            var expected = array.First().Sum();

            return array.All(t => t.Sum() == expected);
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class MagicSquareGenerator
    {

        /// <summary>
        /// 生成实例
        /// </summary>
        /// <param name="size"></param>
        /// <param name="outstr"></param>
        /// <returns></returns>
        public List<List<int>> Generate(int size,out string outstr)
        {
            var g = new Generator();
            var s = new Splitter();
            var v = new Verifier();

            var square = new List<List<int>>();

            do
            {
                square = new List<List<int>>();
                for (int i = 0; i < size; ++i)
                    square.Add(g.Generate(size));
            } while (!v.Verify(s.Split(square)));

            string str = SquareToString(square);
            outstr = str;
            //Console.WriteLine(str);
            return square;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="square"></param>
        /// <returns></returns>
        private string SquareToString(List<List<int>> square)
        {
            var sb = new StringBuilder();
            foreach (var row in square)
            {
                sb.AppendLine(string.Join(" ",
                  row.Select(x => x.ToString())));
            }

            return sb.ToString();
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class MyVerifier
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public bool Verify(List<List<int>> array)
        {
            if (!array.Any()) return false;

            var rowCount = array.Count;
            var colCount = array[0].Count;

            var expected = array.First().Sum();

            for (var row = 0; row < rowCount; ++row)
                if (array[row].Sum() != expected)
                    return false;

            for (var col = 0; col < colCount; ++col)
                if (array.Select(a => a[col]).Sum() != expected)
                    return false;

            var diag1 = new List<int>();
            var diag2 = new List<int>();
            for (var r = 0; r < rowCount; ++r)
                for (var c = 0; c < colCount; ++c)
                {
                    if (r == c)
                        diag1.Add(array[r][c]);
                    var r2 = rowCount - r - 1;
                    if (r2 == c)
                        diag2.Add(array[r][c]);
                }

            return diag1.Sum() == expected && diag2.Sum() == expected;
        }
    }

  

调用:

 //外观模式Facade Pattern
            Console.WriteLine("***外观模式 Facade Pattern Demo.***\n");            
            //Making a Milano robot with green color.
            RobotFacade facade = new RobotFacade("Milano","green");
            facade.ConstructRobot();
            //Making a robonaut robot with default steel color.           
            facade = new RobotFacade("Robonaut");
            facade.ConstructRobot();
            //Destroying one robot
            facade.DestroyRobot();
            //Destroying another robot
            facade.DestroyRobot();
            //This destrcution attempt should fail.
            facade.DestroyRobot();


            //
            string geovindu = "";
            var gen = new MagicSquareGenerator();
            var square = gen.Generate(3,out geovindu);

            Console.WriteLine(geovindu);

            var v = new MyVerifier(); // prevents cheating :)
            Console.WriteLine(v.Verify(square));

            Console.ReadLine();

  

输出:

***外观模式 Facade Pattern Demo.***

Robot creation through facade starts...(造造一个)
Constructing one Milano robot.
Robot creation finished.
Total number of robot created at this moment:(目前机器人总数为)1
Painting the robot with your favourite green color.

Robot creation through facade starts...(造造一个)
Constructing one Robonaut robot.
Robot creation finished.
Total number of robot created at this moment:(目前机器人总数为)2
The default color steel is set for the robot.

Making an attempt to destroy one robot using the facade now.(损坏一个)
Attempting to remove the colors from the robot.
Robot's destruction process is over.剩余总数为:1

Making an attempt to destroy one robot using the facade now.(损坏一个)
Attempting to remove the colors from the robot.
Robot's destruction process is over.剩余总数为:0

Making an attempt to destroy one robot using the facade now.(损坏一个)
Attempting to remove the colors from the robot.
All robots are destroyed already.所有都已经损坏,没有可以做的。
Color removal operation will not continue.

5 5 5
5 5 5
5 5 5

True

  

标签:core,Console,Pattern,robot,var,Facade,new,array,public
From: https://www.cnblogs.com/geovindu/p/16756796.html

相关文章

  • ASP .NET CORE WEB 部署到Docker
    一、新建asp.net core web 网站,二、新建个dockerfile文件 FROMmcr.microsoft.com/dotnet/sdk:6.0ASbuildWORKDIR/appWORKDIR/srcCOPY..RUNdotnetres......
  • CSharp: Adapter Pattern in donet core 3
     ///<summary>///适配器模式AdapterPatternA///geovindu,GeovinDuedit///</summary>interfaceIRectangle{voidAboutMe(......
  • SparkCore:累加器和广播变量
    累加器累加器(分布式共享只写变量):用来把Executor端变量信息聚合到Driver端。在Driver程序中定义的变量,在Executor端的每个Task都会得到这个变量的一份新的副本,每......
  • Servlet—— urlPattern配置
    ServleturlPattern配置  Servlet要想被访问,必须配置其访问路径(urlPattern)  1、一个Servlet可以配置多个urlPattern      2、urlPattern配置规则   ......
  • Asp-Net-Core开发笔记:集成Hangfire实现异步任务队列和定时任务
    前言最近把Python写的数据采集平台往.NetCore上迁移,原本的采集任务使用多进程+线程池的方式来加快采集速度,使用Celery作为异步任务队列兼具定时任务功能,这套东西用着还行......
  • CSharp: Abstract Factory in donet core 3
     ///<summary>///AbstractFactory抽像工厂///geovindu,GeovinDueidt///</summary>publicinterfaceIShape{voidDraw();......
  • ASP.NET Core 中的 Request Feature
    ASP.NETCore中的RequestFeature​​https://docs.microsoft.com/en-us/aspnet/core/fundamentals/request-features?view=aspnetcore-6.0​​在应用程序对象和中间件中......
  • CSharp: QuestPDF create pdf file in donet core 6
     ///<summary>///geovindu,GeovinDu,涂聚文Edit///</summary>publicclassDuModel{privatestringname;......
  • CSharp: Factory Method Pattern in donet core 3
     #regionAnimalHierarchy/**BoththeDogandTigerclasseswill*implementtheIAnimalinterfacemethod.*////<summary>......
  • [AGC041D] Problem Scores
    StOKubic神发现主要限制在第三个限制,考虑变形一下限制要求,问题转化为要求序列的\(k=\lfloor\dfrac{n}{2}\rfloor\),的前\(k+1\)项的和,大于后\(k\)项的和。动......