private void Start() { StrategyContext context = new StrategyContext(); context.strategy = new ConcreteStrategyA(); context.Calculate(); }
public async Task <IActionResult> DeleteAsync(int id, CancellationToken cancellationToken) { var request = new ExcluiTerrenoRequest(id); await StrategyContext.HandlerAsync <ExcluiTerrenoRequest, DefaultResponse>(request, cancellationToken); return(await ApiResponseAsync(Ok())); }
public Order CreateAnOrder(Destination destination, Product product, List <Transport> suitableTransport) { Func <Transport, Order> getOrderByTransport = GetOrderByInvolvedTransport; StrategyContext strategyContext = new StrategyContext(new StandartLogic()); if (!suitableTransport.Select(transport => transport.InTheShop).Any()) { strategyContext.CurrentStrategy = new NoTransportLogic(); Order newOrder = strategyContext.CurrentStrategy.ProcessTheOrder(new PreprocessedOrder(destination, product, suitableTransport), getOrderByTransport); newOrder.Status = new OrderStatus() { ID = 0, Status = "В обробці" }; return(newOrder); } else { Order newOrder = strategyContext.CurrentStrategy.ProcessTheOrder(new PreprocessedOrder(destination, product, suitableTransport), getOrderByTransport); newOrder.Status = new OrderStatus() { ID = 0, Status = "В обробці" }; //AddOrder(newOrder); return(newOrder); } }
void Start() { StrategyContext strategyContext = new StrategyContext(); strategyContext.strategy = new ConcreteStrategyA(); strategyContext.Cal(); }
static void Main(string[] args) { StrategyContext strategyContext1 = new StrategyContext(); strategyContext1.SetStrategy(new CommonPersonStrategy()); Console.WriteLine(strategyContext1.GetFinalPrice(10.1)); StrategyContext strategyContext2 = new StrategyContext(); strategyContext1.SetStrategy(new StudentStrategy()); Console.WriteLine(strategyContext2.GetFinalPrice(10.1)); StrategyContext strategyContext3 = new StrategyContext(); strategyContext1.SetStrategy(new OldPersonStrategy()); Console.WriteLine(strategyContext3.GetFinalPrice(10.1)); #region 简单工厂与策略模式的结合 //StrategyContext strategyContext1 = new StrategyContext(PersonEnum.Common); //Console.WriteLine(strategyContext1.GetFinalPrice(10.1)); //StrategyContext strategyContext2 = new StrategyContext(PersonEnum.Student); //Console.WriteLine(strategyContext2.GetFinalPrice(10.1)); //StrategyContext strategyContext3 = new StrategyContext(PersonEnum.OldMen); //Console.WriteLine(strategyContext3.GetFinalPrice(10.1)); //Console.WriteLine(new StrategyContext(PersonEnum.Common).GetFinalPrice(20.1)); //Console.WriteLine(new StrategyContext(PersonEnum.Student).GetFinalPrice(20.1)); //Console.WriteLine(new StrategyContext(PersonEnum.OldMen).GetFinalPrice(20.1)); #endregion Console.ReadLine(); }
static void ShowStrategyPattern(State eParam, string sParam) { StrategyContext stateContext = new StrategyContext(); StrategyBase strategyBase = null; switch (eParam) { case State.State1: strategyBase = new StrategyOne(); break; case State.State2: strategyBase = new StrategyTwo(); break; case State.State3: strategyBase = new StrategyThree(); break; default: throw new Exception("int参数只能是1,2,3"); } strategyBase.Invoke(eParam, sParam);//可以这么做,但这样就不能额外做一些其他的操作了 stateContext.Invoke(eParam, sParam, strategyBase); }
public static void DisplayRoute(this StrategyContext c, Route r, Points p) { try{ Console.WriteLine("--------------------------------"); if (c is null) { Console.WriteLine("The Context is null. We could not resolve the algorithm!"); return; } Console.WriteLine($"The algorithm is {c.getStrategyName}"); if (r is null) { Console.WriteLine($"The route is null. There is no route between {p.LocationFrom} and {p.LocationTo} !"); return; } Console.WriteLine($"Between {p.LocationFrom} and {p.LocationTo} with {r.Budget.ToString()}euro you will get in {r.TimeInMinutes.ToString()} minutes"); var s = new StringBuilder(); Console.WriteLine($"The route is:{r.RoutePath}"); Console.WriteLine("--------------------------------"); } catch (Exception ex) { Console.WriteLine(" - There was an error trying to display the result."); Console.WriteLine($" - Error: {ex.Message}"); } }
internal void Start(StrategyContext strategyContext) { _strategy = _strategyFactory.GetStrategy( strategyContext.StrategyName, async(trades, candle) => { //TODO: move messages to on sell event await _telegram.SendMessageAsync($"{strategyContext.Market.ToUpperInvariant()} Buy signal @ {candle.Close} Will buy? {!trades.Any() || trades[trades.Count - 1].Direction == TradeDirection.Sell}"); return(!trades.Any() || trades[trades.Count - 1].Direction == TradeDirection.Sell); }, async(trades, candle) => { await _telegram.SendMessageAsync($"{strategyContext.Market.ToUpperInvariant()} Sell Signal @ {candle.Close} Will sell? {trades.Any() && trades[trades.Count - 1].Direction == TradeDirection.Buy}"); return(trades.Any() && trades[trades.Count - 1].Direction == TradeDirection.Buy); }); var cancellationToken = _cancellationTokenSource.Token; Task.Run(() => ExecuteStrategy(strategyContext, cancellationToken), cancellationToken); // For now I dont use websockts because too fast updates, maybe I should only take into consideration closed candles for signals? // Maybe add 2 modes and test how they perform in the market //candles.ForEach(c => _candles.Add(c.OpenTime, c)); //var subscription = new BinanceKLineSubscription() //{ // Symbol = strategyContext.Market.ToLowerInvariant(), // Interval = "1h" //}; //await _binanceApi.ConnectToWebSockets(subscription, OnCandleUpdate, cancellationToken); }
public void StrategyMethod() { StrategyContext context = new StrategyContext(); context.Write("aaaaaaaaaaaaaaa"); context.Write("aaaaa"); }
public AccountController(UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager, KeyvaultContext db) { this.userManager = userManager; this.signInManager = signInManager; _db = db; sql = new StrategyContext(new KeyvaultSqlRepository(_db)); }
public async Task <IActionResult> PostAsync([FromBody] EmpreendimentoVM empreendimento, CancellationToken cancellationToken) { var request = Mapper.Map <CadastraEmpreendimentoRequest>(empreendimento); await StrategyContext.HandlerAsync <CadastraEmpreendimentoRequest, DefaultResponse>(request, cancellationToken); return(await ApiResponseAsync(Created("api/v1/empreendimento/1", empreendimento))); }
protected void SaveStrategyContext(string sContext) { string[] arContext = sContext.Split('#'); if (arContext.Length >= 3) { string sSerialId = arContext[0]; string sParams = arContext[1]; string sPostion = arContext[2]; StrategyContext oContext = new StrategyContext(); oContext.Uid = sSerialId; string sParamNames = ""; if (null != delegate_GetParams) { sParamNames = delegate_GetParams(m_sStrategyName); } oContext.StrategyName = m_sStrategyName; StrategyArbitrageSerial oSerail = new StrategyArbitrageSerial(); oContext.Params = oSerail.ParseParam(sParamNames, sParams); oContext.Postions = oSerail.ParsePostion(sPostion); oSerail.Save(oContext); } }
private void Start() { StrategyContext context = new StrategyContext(); context.strategy = new ConcreateStrategyB(); context.Cal(); }
private void button1_Click(object sender, EventArgs e) { int hesap; hesap = (int)(dateTimePicker2.Value.ToOADate() - dateTimePicker1.Value.ToOADate()); DateTime t1 = dateTimePicker1.Value.Date; DateTime t2 = dateTimePicker2.Value.Date; var fark = t2 - t1; if (fark.Days <= 30) { StrategyKiralama k = new kiralama_gun(); StrategyContext con = new StrategyContext(k); textBox5.Text = Convert.ToString(con.contex(hesap)); } else if (fark.Days > 30 && fark.Days <= 365) { StrategyKiralama k = new kiralama_ay(); StrategyContext con = new StrategyContext(k); textBox5.Text = Convert.ToString(con.contex(hesap)); } else if (fark.Days > 365) { StrategyKiralama k = new kiralama_yıl(); StrategyContext con = new StrategyContext(k); textBox5.Text = Convert.ToString(con.contex(hesap)); } }
public StrategyManagementService(IServiceScopeFactory scopeFactory, ILogger <StrategyManagementService> logger, IMapper mapper) : base(TimeSpan.FromMilliseconds(TickFrequencyMilliseconds), logger) { _logger = logger; _mapper = mapper; _scope = scopeFactory.CreateScope(); _context = _scope.ServiceProvider.GetRequiredService <StrategyContext>(); }
public static void Main() { var context = new StrategyContext(new FirstStrategy()); context.Execute(); context.Strategy = new SecondStrategy(); context.Execute(); }
/// <summary> /// 策略模式 /// </summary> void strategy() { var context = new StrategyContext(new StrategyImpls.Strategy1Impl()); context.Make(); context = new StrategyContext(new StrategyImpls.Strategy2Impl()); context.Make(); }
public void DoStuff() { var context = new StrategyContext(new Strategy0()); context.Execute(); context.SetStrategy(new Strategy1()); context.Execute(); }
private void Start() { StrategyContext context = new StrategyContext(); context.Strategy = new StrategyA(); context.Cal(); context.Strategy = new StrategyB(); context.Cal(); }
static void Main() { Console.WriteLine("Factory"); //------------------------------Factory Pattern Console.WriteLine("Enter Add, subtract or divide"); CalculateFactory factory = new CalculateFactory(); ICalculate obj = factory.GetCalculation(Console.ReadLine()); obj.Calculate(10, 10); Console.WriteLine("Singleton"); //------------------------------Singleton Logger ob1 = Logger.Instance; Logger ob2 = Logger.Instance; Console.WriteLine(ob1.GetHashCode()); Console.WriteLine(ob2.GetHashCode()); Console.WriteLine("TemplateMethod"); //------------------------------TemplateMethod ExcelFile objExcel = new ExcelFile(); objExcel.ReadProcessAndSave(); TextFile objText = new TextFile(); objText.ReadProcessAndSave(); Console.WriteLine("Adapter"); //------------------------------Adapter Adaptee adaptee = new Adaptee(); ITarget target = new Adapter(adaptee); target.GetRequest(); Console.WriteLine("Facade"); //------------------------------Facade var searchEngineFacade = new SearchEngineFacade(); var searchingResults = searchEngineFacade.GetSearchResults("My query"); Console.WriteLine(searchingResults); Console.WriteLine("StrategyPattern"); //------------------------------Strategy StrategyContext context; context = new StrategyContext(new ConcreteStrategyA()); context.ContextInterface(); context = new StrategyContext(new ConcreteStrategyB()); context.ContextInterface(); context = new StrategyContext(new ConcreteStrategyC()); context.ContextInterface(); }
public MainViewModel() { ViewLoaded += OnViewLoaded; UserSaving += OnUserSaving; RiskSaving += OnRiskSaving; StrategySaving += OnStrategySaving; Client = SingletonClient.GetInstance(this).Client; RiskContext = new RiskContext(); StrategyContext = new StrategyContext(); }
private static string GetWord(string number, WordNotation notation) { StrategyContext strategy = new StrategyContext(); if (notation == WordNotation.Us) { strategy.SetNewStrategy(new UsCurrencyStrategy()); } return(strategy.GetWord(number)); }
public void UpdateQuality() { foreach (var item in Items) { var context = new StrategyContext(item.Name); var result = context.Update(item); item.SellIn = result.sellIn; item.Quality = result.quality; } }
public void TestMethodStrategy() { StrategyContext context; context = new StrategyContext(new ConcreteStrategyA()); context.ContextInterface(); context = new StrategyContext(new ConcreteStrategyB()); context.ContextInterface(); }
void PayReceipt(User client) { if (client.Order.Products.Count == 0) { Console.WriteLine("You have not ordered yet!"); } ClientReport clientReport = new ClientReport(); clientReport.Visit(client.Order); float totalPrice = clientReport.TotalPrice; if (Enum.IsDefined(typeof(EOfferType), client.OfferType)) { StrategyContext strategyContext = new StrategyContext(totalPrice); totalPrice = (float)strategyContext.ApplyStrategy(client.OfferType); } totalPrice = (float)Math.Round(totalPrice, 2); CashIn(totalPrice, GetMoneyType()); GetTotalCash(); DataExporter exporter = null; Console.WriteLine("In what format do you want your reciept? \n" + "1 -> txt\n" + "2 -> pdf\n"); int option = Convert.ToInt32(Console.ReadLine()); switch (option) { case 1: exporter = new Txt_Bill_Exporter(); break; case 2: exporter = new PDF_Bill_Exporter(); break; default: exporter = new Txt_Bill_Exporter(); break; } ApplicationMode.Instance.sendAction($"Client {client.Name} paid order: {totalPrice}"); List <BurgerDecorator> burgers = client.Order.Products; exporter.ExportFormatedData($"{client.Name}'s reciept", burgers, $"Total: {totalPrice}"); }
public static Route ResolveRoute(this StrategyContext c, Points p) { try{ return(c.getRoute(p.LocationFrom, p.LocationTo)); } catch (Exception ex) { Console.WriteLine(" - There was an error trying to get the route."); Console.WriteLine($" - Error: {ex.Message}"); } return(null); }
public async Task <IActionResult> GetByIdAsync(int id, CancellationToken cancellationToken) { var response = Mapper.Map <EmpreendimentoVM>(await StrategyContext.HandlerAsync <RetornaEmpreendimentoQuery, RetornarEmpreendimentoQueryResponse>(new RetornaEmpreendimentoQuery(id), cancellationToken)); if (response == null) { return(await ApiResponseAsync(NotFound())); } return(await ApiResponseAsync(Ok(response))); }
public async Task <IActionResult> GetByIdAsync(long id, CancellationToken cancellationToken) { RetornaTerrenoQueryResponse response = await StrategyContext .HandlerAsync <RetornaTerrenoQuery, RetornaTerrenoQueryResponse>(new RetornaTerrenoQuery(id), cancellationToken); if (response == null) { return(await ApiResponseAsync(NotFound())); } return(await ApiResponseAsync(Ok(response))); }
private static void HandleStrategy() { //创建一个策略 StrategyContext context = new StrategyContext(new FileLog()); context.Write("aaaaaabbbbbb"); //创建另一个策略 context = new StrategyContext(new DBLog()); context.Write("aaaaaabbbbbb"); Console.Read(); }
/// <summary> /// Used for converting integer number to Roman Representation /// </summary> /// <param name="num">Number with limit 1-4999</param> /// <returns>Return Roman Representation of Number</returns> public static string ToRoman(int num) { if (num < 1 || num > 4999) { throw new Exception("Number Range must be Between 1-4999"); } StrategyContext strategy = new StrategyContext(); strategy.SetNewStrategy(new RomanStrategy()); return(strategy.GetWord(num.ToString())); }
public void Main() { var context = new StrategyContext(); context.SwitchStrategy(); var r = new Random(37); for (var i = StrategyContext.start; i <= StrategyContext.start + 15; i++) { if (r.Next(3) == 2) { Console.Write("|| "); context.SwitchStrategy(); } Console.Write(context.Algorithm() + " "); } Console.WriteLine(); }
public int Move(StrategyContext c) { return --c.Counter; }