Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var strategyName = GetParam(args, "-r");
            var fileName     = GetParam(args, "-f");

            IStrategy strategy = StrategyFactory.GetStrategy(strategyName);

            string[] answers = GetAnswers(fileName);

            new Chat(strategy, answers).Start();
        }
Ejemplo n.º 2
0
        public void CreateStrategy_當傳入參數deliveryType為PostOffice時_應回傳PostOfficeStrategy的實體()
        {
            // Arrange
            var deliveryType = DeliveryTypeEnum.PostOffice;

            // Act
            var actual = StrategyFactory.CreateStrategy(deliveryType);

            // Assert
            actual.Should().BeOfType <PostOfficeStrategy>();
        }
Ejemplo n.º 3
0
        public void CreateStrategy_當傳入參數deliveryType為KTJ時_應回傳KtjStrategy的實體()
        {
            // Arrange
            var deliveryType = DeliveryTypeEnum.KTJ;

            // Act
            var actual = StrategyFactory.CreateStrategy(deliveryType);

            // Assert
            actual.Should().BeOfType <KtjStrategy>();
        }
 protected virtual void NewGame()
 {
     pairNum     = (row - 2) * (col - 2) / 2;
     this.matrix = CoreGame.CreateMatrix(row, col);
     if (CoreGame.GetAvailablePair(this.matrix).Count == 0)
     {
         ResetMap();
     }
     gameStrategy = StrategyFactory.CreateInstance(GetGameStrategy(level));
     mapUI.Initialize(matrix, this, (GameStrategy)level);
     remainTime = matchTime;
 }
Ejemplo n.º 5
0
        public MainWindow()
        {
            InitializeComponent();

            IEnumerable <IStrategy> strategies = StrategyFactory.CreateAllStrategies();

            IEnumerable <IConstrain> constrains = ConstrainFactory.CreateNormalSudokuContrains(strategies);

            _board = new Board(constrains);

            loadUi();
        }
        /// <summary>
        /// 計算運費。
        /// </summary>
        /// <param name="deliveryItem">宅配資料。</param>
        /// <returns>
        /// 運費。
        /// </returns>
        /// <exception cref="ArgumentNullException">deliveryItem - 請檢查 deliveryItem 參數。</exception>
        public double Calculate(DeliveryEntity deliveryItem)
        {
            if (deliveryItem == null)
            {
                throw new ArgumentNullException(nameof(deliveryItem), $"請檢查 {nameof(deliveryItem)} 參數。");
            }

            var    strategy = StrategyFactory.CreateStrategy(deliveryItem.DeliveryType);
            double fee      = strategy.Calculate(deliveryItem);

            return(fee);
        }
 protected override void NewGame()
 {
     pairNum            = (row - 2) * (col - 2) / 2;
     this.matrix        = CoreGame.CreateMatrix(row, col);
     currentPairCellIds = CoreGame.GetAvailablePair(this.matrix);
     if (currentPairCellIds.Count == 0)
     {
         ResetMap();
     }
     gameStrategy = StrategyFactory.CreateInstance(GetGameStrategy(level));
     mapUI.Initialize(matrix, this, GetGameStrategy(level));
 }
Ejemplo n.º 8
0
        public static void Main()
        {
            IReader             reader           = new ConsoleReader();
            IWriter             writer           = new ConsoleWriter();
            IStrategy           additionStrategy = new AdditionStrategy();
            IStrategyFactory    factory          = new StrategyFactory();
            PrimitiveCalculator calculator       = new PrimitiveCalculator(additionStrategy, factory);

            IRunnable engine = new Engine(calculator, reader, writer);

            engine.Run();
        }
Ejemplo n.º 9
0
        public void CreateStrategy_當傳入參數deliveryType的列舉值未定義宅配策略時_應拋出ArgumentException的例外狀況()
        {
            // Arrange
            var deliveryType = (DeliveryTypeEnum)99;
            var message      = $"請檢查 deliveryType 參數。{Environment.NewLine}參數名稱: deliveryType";

            // Act
            Action action = () => StrategyFactory.CreateStrategy(deliveryType);

            // Assert
            action.ShouldThrow <ArgumentException>().And.Message.Should().Be(message);
        }
Ejemplo n.º 10
0
        public void DefaultItemsShouldDecreaseSellInAndQuality()
        {
            var item = new Item {
                Name = "+5 Dexterity Vest", SellIn = 10, Quality = 20
            };
            var strategy = StrategyFactory.GetStrategy(item);

            strategy.UpdateQuality();

            Assert.Equal(item.SellIn, 9);
            Assert.Equal(item.Quality, 19);
            Assert.InRange(item.Quality, 0, 50);
        }
Ejemplo n.º 11
0
        public void SulfurasDoesNotAlterSellInNorQuality()
        {
            var item = new Item {
                Name = "Sulfuras, Hand of Ragnaros", SellIn = 0, Quality = 80
            };
            var strategy = StrategyFactory.GetStrategy(item);

            strategy.UpdateQuality();

            Assert.Equal(item.SellIn, item.SellIn);
            Assert.Equal(item.Quality, item.Quality);
            Assert.Equal(item.Quality, 80);
        }
Ejemplo n.º 12
0
        public void AgedBrieShouldDecreaseSellInAndIncreaseQuality()
        {
            var item = new Item {
                Name = "Aged Brie", SellIn = 2, Quality = 0
            };
            var strategy = StrategyFactory.GetStrategy(item);

            strategy.UpdateQuality();

            Assert.Equal(item.SellIn, 1);
            Assert.Equal(item.Quality, 1);
            Assert.InRange(item.Quality, 0, 50);
        }
Ejemplo n.º 13
0
        public void ConjuredShouldDecreaseQualityTwiceAsFast()
        {
            var item = new Item {
                Name = "Conjured Mana Cake", SellIn = 3, Quality = 6
            };
            var strategy = StrategyFactory.GetStrategy(item);

            strategy.UpdateQuality();

            Assert.Equal(item.SellIn, 2);
            Assert.Equal(item.Quality, 4);
            Assert.InRange(item.Quality, 0, 50);
        }
Ejemplo n.º 14
0
        public void Configuration_StrategyFactory_tests()
        {
            string prefix = "RTSX";

            IGenericFactory <StrategyHeader> factory = new StrategyFactory(prefix);

            StrategyHeader strategyHeader = factory.Make();

            Assert.AreEqual(1, strategyHeader.Id);
            Assert.AreEqual("Break out RTS", strategyHeader.Description);
            Assert.AreEqual("BP12345-RF-01", strategyHeader.Portfolio);
            Assert.AreEqual("RTS-9.13_FT", strategyHeader.Symbol);
            Assert.AreEqual(15, strategyHeader.Amount);
        }
Ejemplo n.º 15
0
        public static List <IStrategy> GetConfigurations()
        {
            List <IStrategy> strategyList          = new List <IStrategy>();
            IFactory         xChangeObjectFactory  = null;
            IFactory         strategyObjectFactory = null;
            IStrategy        stratObj = null;

            //  IExchange xChangeObj = null;

            using (StreamReader file = File.OpenText(configFile))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                }


            var rootObject = JsonConvert.DeserializeObject <ConfigRoot>(jsonObject.ToString());

            GlobalConfig.SetRootConfig(rootObject);

            //Do Validations here.....  ************************************ NEED CONFIG VALIDATIONS HERE  *********************

            //NEED CONFIG VALIDATIONS HERE

            //******************************************************************************************************************

            foreach (ExchangeConfig xChng in rootObject.Exchanges)
            {
                if (xChng.ActiveStatus)
                {
                    xChangeObjectFactory = new ExchangeFactory();
                    //xChangeObj = xChangeObjectFactory.GetObject<IExchange>(xChng);
                    foreach (StrategyConfig strgyItem in xChng.Strategies)
                    {
                        strategyObjectFactory = new StrategyFactory();
                        if (strgyItem.ActiveStatus)
                        {
                            stratObj = strategyObjectFactory.GetObject <IStrategy>(strgyItem);
                            //xChng.UniqueStrategyId = stratObj.GetStrategyId();
                            stratObj.SetExchangeDetails(xChangeObjectFactory.GetObject <IExchange>(xChng));
                            stratObj.SetConfigPath(configFile);
                            //stratObj.SetStrategyId();
                            strategyList.Add(stratObj);
                        }
                    }
                }
            }
            return(strategyList);
        }
Ejemplo n.º 16
0
        public Task StoreAsync <TDocument, TId, TContent>(Collection <TDocument, TId, TContent> collection)
            where TDocument : Document <TContent, TId>, new()
            where TContent : class
        {
            var commands = collection
                           .GetModifiedDocuments()
                           .Select(doc => StrategyFactory.GetStrategy(collection, doc))
                           .Select(s => s.GetCommand());

            var commandsString = string.Join(";", commands);

            // TODO execute commands

            return(Task.CompletedTask);
        }
Ejemplo n.º 17
0
 public TimeScheduleWorkflowManager()
 {
     try
     {
         ConfigurationSetting.Initialize();
         strategryFactory = new StrategyFactory();
         timeSchedule     = new TimeSchedule(strategryFactory.Create());
         timeSchedule.LoadRequests(ConfigurationSetting.InputFile);
     }
     catch (Exception ex)
     {
         Console.WriteLine(UNEXPECTEDFAILURE);
         Console.WriteLine(ex);
     }
 }
Ejemplo n.º 18
0
    protected void Bind()
    {
        //lblRes.Text = ResourceManager.GetString("AddAComment");
        SiteSettings settings = SiteSettingsManager.GetSiteSettings();

        txtSiteName.Text   = settings.SiteName;
        txtSmtpServer.Text = settings.SmtpServer;
        txtUserName.Text   = settings.SmtpServerUserName;
        txtPwd.Text        = settings.SmtpServerPassword;

        DropDownList1.DataSource     = StrategyFactory.GetStrategies();
        DropDownList1.DataTextField  = "Text";
        DropDownList1.DataValueField = "Name";
        DropDownList1.DataBind();
    }
Ejemplo n.º 19
0
        public void ItCreates_HardStrategy()
        {
            // Prepare :

            var factory = new StrategyFactory();

            // Act:

            var strategy = factory.Create(Strategies.HardStrategy);

            // Assert:

            Assert.NotNull(strategy);
            Assert.IsType<HardStrategy>(strategy);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Start the storage and load the type strategies
        /// </summary>
        public void Start()
        {
            _types = ReflectionTool.GetPublicClasses <ProductType>().ToDictionary(t => t.Name, t => t);

            // Create type strategies
            foreach (var config in Config.TypeStrategies)
            {
                var strategy = StrategyFactory.CreateTypeStrategy(config);
                TypeStrategies[config.TargetType]   = strategy;
                TypeConstructors[config.TargetType] = ReflectionTool.ConstructorDelegate <ProductType>(strategy.TargetType);
            }
            // Create instance strategies
            foreach (var config in Config.InstanceStrategies)
            {
                var strategy = StrategyFactory.CreateInstanceStrategy(config);
                InstanceStrategies[config.TargetType] = strategy;
            }
            // Create link strategies
            foreach (var config in Config.LinkStrategies)
            {
                var strategy = StrategyFactory.CreateLinkStrategy(config);
                LinkStrategies[config.TargetType][config.PartName] = strategy;

                var property = strategy.TargetType.GetProperty(config.PartName);
                var linkType = property.PropertyType;
                // Extract element type from collections
                if (typeof(IEnumerable <IProductPartLink>).IsAssignableFrom(linkType))
                {
                    linkType = linkType.GetGenericArguments()[0];
                }
                // Build generic type
                if (linkType.IsInterface && linkType.IsGenericType)
                {
                    var genericElement = linkType.GetGenericArguments()[0];
                    linkType = typeof(ProductPartLink <>).MakeGenericType(genericElement);
                }

                LinkConstructors[$"{config.TargetType}.{config.PartName}"] = ReflectionTool.ConstructorDelegate <IProductPartLink>(linkType);
            }
            // Create recipe strategies
            foreach (var config in Config.RecipeStrategies)
            {
                var strategy = StrategyFactory.CreateRecipeStrategy(config);
                RecipeStrategies[config.TargetType] = strategy;

                RecipeConstructors[config.TargetType] = ReflectionTool.ConstructorDelegate <IProductRecipe>(strategy.TargetType);
            }
        }
Ejemplo n.º 21
0
        public IStrategyFactory CreateFactory(StrategyFactoryType tp)
        {
            switch (tp)
            {
            case StrategyFactoryType.Kd:
            {
                KdAdjustFactory factory = new KdAdjustFactory();
                factory.Init();

                return(factory);
            }

            case StrategyFactoryType.Normal:
            {
                StrategyFactory factory = new StrategyFactory();
                factory.Init();

                return(factory);
            }

            case StrategyFactoryType.RiseDown:
            {
                RiseDownAdjustFactory factory = new RiseDownAdjustFactory();
                factory.Init();

                return(factory);
            }

            case StrategyFactoryType.Spike:
            {
                SpikeAdjustFactory factory = new SpikeAdjustFactory();
                factory.Init();

                return(factory);
            }

            case StrategyFactoryType.Volume:
            {
                VolumeAdjustFactory factory = new VolumeAdjustFactory();
                factory.Init();

                return(factory);
            }

            default:
                return(null);
            }
        }
Ejemplo n.º 22
0
        public void BackStagePassesShouldMakeQuality0WhenSellInOrLess()
        {
            var item = new Item
            {
                Name    = "Backstage passes to a TAFKAL80ETC concert",
                SellIn  = 0,
                Quality = 20
            };
            var strategy = StrategyFactory.GetStrategy(item);

            strategy.UpdateQuality();

            Assert.Equal(item.SellIn, -1);
            Assert.Equal(item.Quality, 0);
            Assert.InRange(item.Quality, 0, 50);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// adds a factory to the list of possible database factories or return the existing factory for the given type and model
        /// </summary>
        /// <param name="type">the type of the factory</param>
        /// <param name = "model">the model for this factory</param>
        /// <param name = "strategyFactory">the strategy for this factory</param>
        public static DatabaseFactory getFactory(string type, Model model, StrategyFactory strategyFactory)
        {
            if (!modelFactories.ContainsKey(model))
            {
                var newFactories = new Dictionary <string, DatabaseFactory>();
                modelFactories.Add(model, newFactories);
            }
            var factories = modelFactories[model];

            if (!factories.ContainsKey(type))
            {
                DatabaseFactory factory = new DatabaseFactory(type, model, strategyFactory);
                factories.Add(type, factory);
            }
            return(factories[type]);
        }
Ejemplo n.º 24
0
        public void BackStagePassesShouldDecreaseSellInAndIncreaseQuality()
        {
            var item = new Item
            {
                Name    = "Backstage passes to a TAFKAL80ETC concert",
                SellIn  = 15,
                Quality = 20
            };
            var strategy = StrategyFactory.GetStrategy(item);

            strategy.UpdateQuality();

            Assert.Equal(item.SellIn, 14);
            Assert.Equal(item.Quality, 21);
            Assert.InRange(item.Quality, 0, 50);
        }
Ejemplo n.º 25
0
        public void BackStagePassesShouldIncreaseQuality3TimesAsMuchWhenSellIn5OrLess()
        {
            var item = new Item
            {
                Name    = "Backstage passes to a TAFKAL80ETC concert",
                SellIn  = 5,
                Quality = 20
            };
            var strategy = StrategyFactory.GetStrategy(item);

            strategy.UpdateQuality();

            Assert.Equal(item.SellIn, 4);
            Assert.Equal(item.Quality, 23);
            Assert.InRange(item.Quality, 0, 50);
        }
Ejemplo n.º 26
0
        private static void Main()
        {
            _strategyFactory = new StrategyFactory();
            _ui      = Chat.GetUI();
            _version = Assembly.GetEntryAssembly().GetName().Version;

            _ui.Send("===============================================================================");
            _ui.Send("---------------------------------- Briscola -----------------------------------");
            _ui.Send("-------------------------------- v. " + _version + " ---------------------------------");
            _ui.Send("===============================================================================");
            string cmd;

            do
            {
                _ui.Send("");
                _ui.Send("Cosa vuoi fare?");
                _ui.Send("");
                _ui.Send("  (1) | Partita singola a 2 giocatori (umano/pc)");
                _ui.Send("  (2) | Partita singola a 4 giocatori (umano/pc)");
                _ui.Send("  (3) | Scontro diretto tra Robot");
                _ui.Send("  (4) | Gran Torneo dei Robot");
                _ui.Send("  (x) | Esci");

                cmd = _ui.GetChoice();
                switch (cmd)
                {
                case "1":
                    Run2PlayerGame();
                    break;

                case "2":
                    Run4PlayerGame();
                    break;

                case "3":
                    var numGames = _ui.GetInt("Quante partite vuoi giocare? (default = 100)", 100);
                    RunRobotMatch(numGames);
                    break;

                case "4":
                    var tournamentSingleGames = _ui.GetInt("Quante partite vuoi giocare per ogni match? (default = 1000)", 1000);
                    var tournamentRunner      = new BergerPairing(_strategyFactory, tournamentSingleGames);
                    tournamentRunner.Run();
                    break;
                }
            } while (!IsExit(cmd));
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("Английские слова:");
            Console.WriteLine("Для выхода введите Q");

            var speaker  = new ConsoleSpeaker();
            var listener = new ConsoleListener();

            IStrategyFactory strategyFactory = new StrategyFactory(speaker, listener);
            var strategySelector             = new StrategySelector();
            var worldSource = new XmlWorldSource();

            var appl   = new Appl(strategyFactory, strategySelector, worldSource);
            var result = appl.Run();

            Console.WriteLine("Результат:");
            Console.WriteLine($"Всего слов: {result.AllResults.Count}");

            Console.WriteLine($"Без ошибок: {result.ByBadCount(0, 0).Count()}");
            Console.WriteLine($"С одной ошибкой: {result.ByBadCount(1, 1).Count()}");
            foreach (var word in result.ByBadCount(1, 1))
            {
                Console.WriteLine(word.First);
            }

            Console.WriteLine($"С двумя ошибками: {result.ByBadCount(2, 2).Count()}");
            foreach (var word in result.ByBadCount(2, 2))
            {
                Console.WriteLine(word.First);
            }

            Console.WriteLine($"С тремя ошибками: {result.ByBadCount(3, 3).Count()}");
            foreach (var word in result.ByBadCount(3, 3))
            {
                Console.WriteLine(word.First);
            }

            Console.WriteLine($"Более трех ошибок: {result.ByBadCount(4, null).Count()}");
            foreach (var word in result.ByBadCount(4, null))
            {
                Console.WriteLine(word.First);
            }

            Console.ReadLine();
        }
Ejemplo n.º 28
0
        public MainViewModel()
        {
            var speaker = new SpeakerDummy();
            //var listener = new ListenerDummy();

            IStrategyFactory strategyFactory = new StrategyFactory(speaker, _listener);
            var strategySelector             = new StrategySelector();
            var worldSource = new XmlWorldSource();

            var appl = new Appl(strategyFactory, strategySelector, worldSource);

            _appl = appl;
            //_appl.Run();


            Update();
        }
Ejemplo n.º 29
0
        public TradingPlatform(StrategySettingsFactory settingsFactory
                               , StrategyFactory strategyFactory
                               , PlatformJobsRepository jobRepo
                               , PlatformLogService PlatformLogService
                               )
        {
            this.settingsFactory    = settingsFactory;
            this.strategyFactory    = strategyFactory;
            this.jobRepo            = jobRepo;
            this.PlatformLogService = PlatformLogService;
            this.strategyTokens     = new Dictionary <string, CancellationTokenSource>();

            this.userId = userId;


            this.strategies = new List <IStrategy>();
        }
        public void Run()
        {
            do
            {
                _userInputManager.RequestConfigurationData();
                _simulator.InitRouletteGame(_userInputManager.MinimumBid, _userInputManager.MaximumBid);
                _statisticsManager.Clear();

                do
                {
                    var strategy = StrategyFactory.Create(_userInputManager.Strategy, _userInputManager.Cycles, new Player(_userInputManager.Name, _userInputManager.Budget));
                    var result   = _simulator.ExecuteStrategy(strategy, _userInputManager.StartBet);
                    _statisticsManager.Process(result);
                    _visualizer.ShowStatistics(_statisticsManager.GetStatistics());
                } while (_userInputManager.ShowModal("Run strategy again? (y or n):", "y", "n"));
            } while (_userInputManager.ShowModal("Continue or quit? (Enter or q):", "Enter", "q"));
        }