Fungura amabanga yububiko bwa software hamwe na Mastering Software Architecture: 11 Ibyingenzi Byashushanyije Byasobanuwe .
2. Igishushanyo mbonera - Adaptor
3. Igishushanyo mbonera - Umwubatsi
4. Nigute ushobora gukoresha Urunigi rwinshingano
5. Igishushanyo mbonera - Umutako
6. Igishushanyo mbonera - Uburyo bw'uruganda
7. Igishushanyo mbonera - Iterator
8. Igishushanyo mbonera - Umuhuza
9. Igishushanyo mbonera - Indorerezi
10. Icyitegererezo cyumutungo wambere C # 8.0
11. Igishushanyo mbonera - Singleton
Dukurikije Agatsiko ka Bane, uruganda rudasanzwe rushobora gufatwa nkuruganda rwo gukora inganda.
Igishushanyo mbonera cyuruganda nuburyo bwo kwagura uruganda; birasabwa kunyura muburyo bwuruganda mbere yo gusobanukirwa nigishushanyo mbonera cyuruganda.
Reka dusuzume urugero rumwe rwa Banki iyo ariyo yose ifite ubwoko bwa konti nka Kuzigama na konti zubu. Noneho, reka dushyire mubikorwa urugero twavuze haruguru dukoresheje igishushanyo mbonera cyuruganda.
Ubwa mbere, shyira mu bikorwa ISavingAccount na ICurrentAccount interineti kuburyo bukurikira:
public interface ISavingAccount{ } public interface ICurrentAccount{ }
Kuragwa intera mumasomo hepfo
public class CurrentAccount : ICurrentAccount { public CurrentAccount(string message) { Console.WriteLine(message); } } public class SavingsAccount : ISavingAccount { public SavingsAccount( string message) { Console.WriteLine(message); } }
Reka twandike icyiciro kidasubirwaho hamwe nuburyo budasobanutse kuri buri bwoko bwa konti.
public abstract class AccountTypeFactory { public abstract ISavingAccount SavingAccountFactory(string message); public abstract ICurrentAccount CurrentAccountFactory(string message); }
Noneho, reka dushyire mubikorwa uruganda rwitwa "Bank1Factory," rutanga ishyirwa mubikorwa ryuburyo budafatika.
public class Bank1Factory : AccountTypeFactory { public override ICurrentAccount CurrentAccountFactory(string message) { return new CurrentAccount(message); } public override ISavingAccount SavingAccountFactory(string message) { return new SavingsAccount(message); } }
Igishushanyo mbonera cyuruganda rutandukanye nuburyo bwuruganda rukeneye gushyira mubikorwa uruganda, rusubiza inganda nkuko bisobanurwa.
Noneho ko dufite abstraction zose ninganda zakozwe. Reka dushushanye gutanga uruganda. Nyamuneka shakisha munsi ya kode yerekana kubitanga uruganda, aho uburyo buhoraho buzakora uruganda rushingiye kumazina ya konti.
public class AccountFactoryProvider { public static AccountTypeFactory GetAccountTypeFactory(string accountName) { if (accountName.Contains("B1")) { return new Bank1Factory(); } else return null; } }
Reka dufate urugero rwurutonde rwimibare ya konte aho niba izina rya konte rigizwe na “ B1 ” muburyo busanzwe, noneho bizakoresha urugero rwa Bank1Uruganda rwagarutse binyuze mubitanga uruganda.
static void Main(string[] args) { List<string> accNames = new List<string> { "B1-456", "B1-987", "B2-222" }; for (int i = 0; i < accNames.Count; i++) { AccountTypeFactory anAbstractFactory = AccountFactoryProvider.GetAccountTypeFactory(accNames[i]); if (anAbstractFactory == null) { Console.WriteLine("Invalid " + (accNames[i])); } else { ISavingAccount savingAccount = anAbstractFactory.SavingAccountFactory("Hello saving"); ICurrentAccount currentAccount = anAbstractFactory.CurrentAccountFactory("Hello Current"); } } Console.ReadLine(); }
Niba izina rya konti ridafite "B1" risanzwe, noneho porogaramu izasohoka {{konte Izina}}
Nyamuneka shakisha munsi y'ibisohoka bivuye kode yavuzwe haruguru.
Hello saving B1-456 Hello Current B1-456 Hello saving B1-987 Hello Current B1-987
Ukurikije Agatsiko ka Bane, Adapter Pattern ihindura intera yicyiciro mubice umukiriya asaba.
Muyandi magambo, igishushanyo mbonera cya adaptori gifasha intera idahuye ikora hamwe.
Reka dusuzume urugero rwimiryango ibiri ihuza; X organisation ifata Y, ariko mugihe uhuza code, intera ntishobora guhuza. Dufate ko interineti itanga urutonde rwibikorwa byumuryango Y idahuye na X.
Noneho, igishushanyo mbonera cya adaptori gifasha gukemura iki kibazo kubishyira mubikorwa byoroshye.
Reka dukore urutonde rwibikorwa biva mumuryango Y byahinduwe muburyo abakiriya bakoresha ishyirahamwe X risaba. Icyiciro cyavuzwe haruguru kizwi nka “Adaptee.”
public class OrgYTransactions { public List<string> GetTransactionsList() { List<string> transactions = new List<string>(); transactions.Add("Debit 1"); transactions.Add("Debit 2"); transactions.Add("Debit 3"); return transactions; } }
Icyakabiri, reka dushyireho intego.
public interface ITransactions{ List<string> GetTransactions(); }
Noneho amaherezo, reka dushyire mubikorwa icyiciro cya adapt kuburyo bukurikira.
public class TransAdapter : OrgYTransactions, ITransactions { public List<string> GetTransactions() { return GetTransactionsList(); } }
Nyuma yuko ibyashyizwe mubikorwa byose bimaze gukorwa, reka twumve uburyo bwo gukoresha adapt ya class muri progaramu ya konsole.
class Program { static void Main(string[] args) { ITransactions adapter = new TransAdapter(); foreach (var item in adapter.GetTransactions()) { Console.WriteLine(item); } } }
Niba witegereje neza imikoreshereze ikurikira, twakoresheje intego ya interineti ITransaction hamwe na adapt ya class TransAdapter utarinze kureba uko igice cyagatatu cya OrgYTransaction gisa. Nizo mbaraga zuburyo bwa adaptor igishushanyo gihindura intera yicyiciro mubice umukiriya asaba.
Dukurikije Agatsiko ka Bane, uburyo bwo guhanga “Umwubatsi” butuma umuntu atandukana kandi agakoresha uburyo bwihariye bwo kubaka ikintu.
Reka dufate urugero rwimodoka, kandi uyikoresha yashakaga kubaka moderi ebyiri, ni ukuvuga, SUV na Sedan.
Igishushanyo mbonera cyubaka kiza gikenewe murwego rwo hejuru rwo gukoresha, kandi reka turebe intambwe ku yindi.
Urwego rwimodoka rufite ibintu bikurikira.
public class Car{ public string Name { get; set; } public double TopSpeed { get; set; } public bool IsSUV { get; set; } }
Ubwa mbere, reka dushyire mubikorwa byubaka ibyiciro byongerewe byimodoka zitandukanye nka SUV cyangwa sedan nkuko byakoreshejwe.
public abstract class CarBuilder { protected readonly Car _car = new Car(); public abstract void SetName(); public abstract void SetSpeed(); public abstract void SetIsSUV(); public virtual Car GetCar() => _car; }
Icyiciro cya abstract kigizwe nuburyo bukurikira
Noneho, reka dushyireho uruganda rukoresha icyiciro cya CarBuilder kugirango twubake moderi zitandukanye kandi dusubize urugero rwimodoka yakozwe.
public class CarFactory { public Car Build(CarBuilder builder) { builder.SetName(); builder.SetSpeed(); builder.SetIsSUV(); return builder.GetCar(); } }
Hanyuma, shyira mubikorwa bitandukanye byimodoka.
public class ModelSuv : CarBuilder { public override void SetIsSUV() { _car.IsSUV = true; } public override void SetName() { _car.Name = "Maruti SUV"; } public override void SetSpeed() { _car.TopSpeed = 1000; } }
public class ModelSedan : CarBuilder { public override void SetIsSUV() { _car.IsSUV = false; } public override void SetName() { _car.Name = "Maruti Sedan"; } public override void SetSpeed() { _car.TopSpeed = 2000; } }
Hanyuma, reka dukoreshe igishushanyo mbonera kugirango twubake imiterere yimodoka itandukanye hifashishijwe uruganda.Ubwubatsi (<model>).
static void Main(string[] args) { var sedan = new ModelSedan(); var suv = new ModelSuv(); var factory = new CarFactory(); var builders = new List<CarBuilder> { suv, sedan }; foreach (var b in builders) { var c = factory.Build(b); Console.WriteLine($"The Car details" + $"\n--------------------------------------" + $"\nName: {c.Name}" + $"\nIs SUV: {c.IsSUV}" + $"\nTop Speed: {c.TopSpeed} mph\n"); } }
Imikoreshereze yavuzwe haruguru yerekana uburyo bwiza dushobora kubaka moderi zitandukanye zimodoka dukoresheje igishushanyo mbonera.
Imiterere yimyandikire irashobora kubungabungwa cyane & kwaguka. Niba, mugihe kizaza, dukeneye guteza imbere icyitegererezo gishya, gusa moderi nshya ikeneye kwagura CarBuilder icyiciro, kandi birakozwe.
Nk’uko Agatsiko ka Bane kavuga, gasobanura urunigi rw'inshingano zo gutunganya icyifuzo. Muyandi magambo, ohereza icyifuzo kuva mubintu bikajya mubindi kugeza igihe ikintu cyemeye inshingano zacyo.
Reka dusuzume urugero rwa sisitemu yo gusaba muri sosiyete iyo ariyo yose. Dore urutonde rwibiciro bishobora kwemezwa nande.
100–1000 Rs => Junior/Senior Engineers => Approved by Manager 1001–10000 Rs => Managers => Approved by Senior Manager
Niba amafaranga ari hanze ya 10000, birasabwa kwemererwa bidasanzwe kubayobozi bakuru.
Ikoreshwa ryavuzwe haruguru rirashobora gushyirwa mubikorwa byoroshye ukoresheje Urunigi rwinshingano. Rero, icyiciro cyo gusaba gifite imitungo ikurikira.
public class Claim{ public int Id{get;set;} public double amount{get;set;} }
Ubwa mbere, reka dusobanure imirimo uwasabye ikirego ashobora gukora no gushyiraho urwego rwabakozi ku nzego zitandukanye. Shyira mu bikorwa icyiciro kidafatika nkuko bigaragara hano hepfo
public abstract class ClaimApprover { protected ClaimApprover claimApprover; public void SetHierarchy(ClaimApprover claimApprover) { this.claimApprover = claimApprover; } public abstract void ApproveRequest(Claim claim); }
Nkurikije ikibazo cyo gukoresha, reka dutware icyiciro "junior / mukuru" usaba gusaba. Menya ko iki cyiciro / kugena abakozi bidashobora kwemeza ibirego byose.
public class Junior : ClaimApprover { public override void ApproveRequest(Claim claim) { System.Console.WriteLine("Cannot approve"); } }
Muri ubwo buryo, reka dusobanure ishyirwa mubikorwa rya Manager na Senior Manager.
public class Manager : ClaimApprover { public override void ApproveRequest(Claim claim) { if (claim.amount >= 100 && claim.amount <= 1000) { System.Console.WriteLine($"Claim reference {claim.Id} with amount {claim.amount} is approved by Manager"); } else if (claimApprover != null) { claimApprover.ApproveRequest(claim); } } }
Menya ko ukurikije umubare wamafaranga, niba murwego rwumuyobozi, ikirego gishobora kwemezwa numuyobozi; bitabaye ibyo, icyifuzo kizanyuzwa kumuyobozi mukuru.
public class SeniorManager : ClaimApprover { public override void ApproveRequest(Claim claim) { if (claim.amount > 1000 && claim.amount <= 10000) { System.Console.WriteLine($"Claim reference {claim.Id} with amount {claim.amount} is approved by Senior Manager"); } else { System.Console.WriteLine($"Exceptional approval for Claim reference {claim.Id} with amount {claim.amount} is approved by Senior Manager"); } } }
Muri ubwo buryo ,, niba umubare wamafaranga uri murwego rwumuyobozi mukuru, ikirego gishobora kwemezwa numuyobozi; bitabaye ibyo, kuba uwanyuma mubyiciro, kwemererwa bidasanzwe bikorwa kumafaranga hanze yurwego.
ClaimApprover junior = new Manager(); ClaimApprover sukhpinder = new Manager(); ClaimApprover singh = new SeniorManager(); junior.SetHierarchy(sukhpinder); sukhpinder.SetHierarchy(singh); Claim c1 = new Claim() { amount = 999, Id = 1001 }; Claim c2 = new Claim() { amount = 10001, Id = 1002 }; junior.ApproveRequest(c1); sukhpinder.ApproveRequest(c2);
Claim reference 1001 with amount 999 is approved by Manager Exceptional approval for Claim reference 1002 with amount 10001 is approved by Senior Manager
Ku murongo wa 1 ibisohoka, amafaranga yari murwego, nuko umuyobozi arabyemeza.
Ku murongo wa 2 ibisohoka, nubwo umuyobozi mukuru yabyemeje, amafaranga yari hanze yurwego.
Ukurikije Agatsiko ka Bane, icyitegererezo cyongera inshingano zinyongera kubintu byishuri bigenda neza.
Reka dusuzume urugero rwo kugura imodoka ifite agaciro ka miliyoni icumi; isosiyete itanga ibintu byinyongera bikurikira.
Hamwe nibindi bintu byiyongereye, igiciro cyimodoka cyiyongera. Reka dushyire mubikorwa imikoreshereze yavuzwe haruguru dukoresheje Decorator Pattern.
Reka dushyire mubikorwa ikibazo cyo gukoresha cyasobanuwe haruguru. Icyambere, sobanura ibyiciro bidasubirwaho Imodoka nuburyo bwibanze.
public abstract class Car{ public abstract int CarPrice(); public abstract string GetName(); }
Tekereza imodoka ntoya irambuye hejuru yimiterere yimodoka.
public class SmallCar : Car{ public override int CarPrice() => 10000; public override string GetName() => "Alto Lxi"; }
Noneho, shyira mubikorwa CarDecorator ukoresheje ibice byimodoka.
public class CarDecorator : Car { protected Car _car; public CarDecorator(Car car) { _car = car; } public override int CarPrice() => _car.CarPrice(); public override string GetName() =>_car.GetName(); }
Noneho, reka dushyireho icyiciro cyihariye kuri buri kintu cyiyongereye kiboneka kumodoka iragwa icyiciro cya CarDecorator.
Nkurikije imikoreshereze yimikoreshereze, ibiranga inyongera ni izuba kandi sisitemu yumuziki igezweho.
Kurenga uburyo nka
Ongeraho ikiguzi cyinyongera cya "sisitemu yumuziki wateye imbere" kubiciro byose byimodoka.
Kuvugurura izina ryimodoka hamwe nizina ryinyongera.
public class AdvanceMusic : CarDecorator { public AdvanceMusic(Car car) : base(car) { } public override int CarPrice() => _car.CarPrice() + 3000; public override string GetName()=> "Alto Lxi with advance music system"; }
Kurenga uburyo nka
public class Sunroof : CarDecorator { public Sunroof(Car car) : base(car) { } public override int CarPrice() => _car.CarPrice() + 2000; public override string GetName() => "Alto Lxi with Sunroof"; }
Kora urugero rwa SmallCar hanyuma usohokemo izina nigiciro cyimodoka.
Car car = new SmallCar(); Console.WriteLine($"Price of car {car.GetName()} : " + car.CarPrice());
Noneho, reka twongere ibintu byongeweho nkuko bigaragara hano hepfo
var car1 = new Sunroof(car); var car2 = new AdvanceMusic(car);
static void Main(string[] args) { Car car = new SmallCar(); Console.WriteLine($"Price of car {car.GetName()} : " + car.CarPrice()); var car1 = new Sunroof(car); Console.WriteLine($"Price of car {car1.GetName()} : " + car1.CarPrice()); var car2 = new AdvanceMusic(car); Console.WriteLine($"Price of car {car2.GetName()} : " + car2.CarPrice()); }
Twishimiye .. !! Washyize mubikorwa neza gukoresha ikoreshwa ukoresheje igishushanyo mbonera.
Ukurikije Agatsiko ka Bane, uburyo bwuruganda butuma subcass igena ikintu cyicyiciro kigomba kuremwa.
Reka dusuzume urugero rwa Banki iyo ari yo yose ifite ubwoko bwa konti nka Kuzigama na konti zubu. Noneho, reka dushyire mubikorwa urugero rwavuzwe haruguru dukoresheje igishushanyo mbonera cyuruganda
Ubwa mbere, kora konti-ubwoko bwa abstract class.
public abstract class AccoutType { public string Balance { get; set; } }
Shyira mubikorwa ibyiciro bya konte no kuzigama uzungura KontiType yerekana ibyiciro nkuko bigaragara hano hepfo.
public class SavingsAccount : AccoutType { public SavingsAccount() { Balance = "10000 Rs"; } } public class CurrentAccount : AccoutType { public CurrentAccount() { Balance = "20000 Rs"; } }
Hanyuma, reka dushyire mubikorwa uruganda, ruzatanga amasezerano afasha kurema ikintu cyicyiciro. Iyi interface nayo izwi nka Rurema.
public interface IAccountFactory { AccoutType GetAccoutType(string accountName); }
Ubwanyuma, andika ishyirwa mubikorwa ryuburyo bwa creator nkuko bigaragara hano hepfo. Icyiciro gishyira mubikorwa umuremyi kizwi nkumuremyi wa beto.
public class AccountFactory : IAccountFactory { public AccoutType GetAccoutType(string accountName) { if (accountName.Equals("SAVINGS", StringComparison.OrdinalIgnoreCase)) { return new SavingsAccount(); } else if (accountName.Equals("CURRENT", StringComparison.OrdinalIgnoreCase)) { return new CurrentAccount(); } else { throw new ArgumentException("Invalid account name"); } } }
Nibyo. Washyize mubikorwa uburyo bwuruganda ukoresheje urugero rwa Banki.
Itsinda rito rizahitamo ikintu cyitwa "KontiType" icyiciro kizakorwa hashingiwe ku izina rya konti.
class Program { static void Main(string[] args) { IAccountFactory accountFactory = new AccountFactory(); var savingAccount = accountFactory.GetAccoutType("SAVINGS"); Console.WriteLine("Saving account balance: " + savingAccount.Balance); var currentAccount = accountFactory.GetAccoutType("CURRENT"); Console.WriteLine("Current account balance: " + currentAccount.Balance); } }
Kurugero, niba izina rya konte ari "SAVINGS," noneho ikintu cyicyiciro cya "SavingAccount" kizaremwa kandi gisubizwe.
Mu buryo nk'ubwo, niba izina rya konte ari "BIKURIKIRA," noneho icyiciro cya "CurrentAccount" icyiciro kizahita gisubizwa.
Saving account balance: 10000 Rs Current account balance: 20000 Rs
Dukurikije Agatsiko ka Bane, uburyo bwa iterater butanga inzira yo kubona igiteranyo cyo guteranya utazi ishyirwa mubikorwa ryacyo.
Reka dufate urugero rwurutonde rwikusanyirizo rwimodoka hamwe numugozi [] umurongo wa moto, dukeneye gushushanya ikintu cyegeranya kugirango umuntu asubire hejuru yikusanyamakuru atazi niba ari urutonde cyangwa umurongo.
Igishushanyo mbonera cya iterator gifasha gukemura iki kibazo aho iterator isanzwe izanyura muburyo butandukanye bwo gukusanya.
Twihweje imikoreshereze yavuzwe haruguru, reka dusobanure imigenzereze yimikorere ikora nkurwego rudasobanutse kurutonde na array iterator.
public interface IVehicleIterator{ void First(); bool IsDone(); string Next(); string Current(); }
Noneho, andika imodoka na moto iteratori ishyira mubikorwa intera yavuzwe haruguru ukurikije ikibazo cyo gukoresha.
public class CarIterator : IVehicleIterator { private List<string> _cars; private int _current; public CarIterator(List<string> cars) { _cars = cars; _current = 0; } public string Current() { return _cars.ElementAt(_current); } public void First() { _current = 0; } public bool IsDone() { return _current >= _cars.Count; } public string Next() { return _cars.ElementAt(_current++); } }
Imashini itera imodoka ishyirwa mubikorwa kurutonde rwa <string> kandi itanga ishyirwa mubikorwa ryuburyo bwa interineti.
Moto iterater ishyirwa mubikorwa hejuru yumurongo [] ikanatanga ishyirwa mubikorwa ryuburyo bwa interineti.
public class MotercycleIterator : IVehicleIterator { private string[] _motercylces; private int _current; public MotercycleIterator(string[] motercylces) { _motercylces = motercylces; _current = 0; } public string Current() { return _motercylces[_current]; } public void First() { _current = 0; } public bool IsDone() { return _current >= _motercylces.Length; } public string Next() { return _motercylces[_current++]; } }
Nyuma yibi byose byavuzwe haruguru bisobanuwe, sobanura ibintu bisanzwe bigizwe na interineti ikora iterater.
public interface IVehicleAggregate{ IVehicleIterator CreateIterator(); }
Hanyuma, andika ibyiciro bishyira mubikorwa byavuzwe haruguru. Ukurikije ikibazo cyo gukoresha, ibyiciro byimodoka na moto bizashyira mubikorwa interineti.
Uburyo bwa agregator interface isubiza iterator bijyanye nkuko bigaragara hano hepfo.
public class Car : IVehicleAggregate { private List<string> _cars; public Car() { _cars = new List<string> { "Car 1", "Car 2", "Car 3" }; } public IVehicleIterator CreateIterator() { return new CarIterator(_cars); } }
Uburyo bwimikorere ya agregator isubiza iterator bijyanye nkuko bigaragara hano hepfo.
public class Motercycle : IVehicleAggregate { private string[] _motercycles; public Motercycle() { _motercycles = new[] { "Bike 1", "Bike 2", "Bike 3" }; } public IVehicleIterator CreateIterator() { return new MotercycleIterator(_motercycles); } }
Uburyo bwa PrintVehicles reba niba! Iterator.Byakozwe noneho bisohora icyegeranyo. Ntakibazo icyo twakusanyije duhura nacyo, shyira mubikorwa uburyo bwa mbere, IsDone, na Ibikurikira.
static void Main(string[] args) { IVehicleAggregate car = new Vehicles.Car(); IVehicleAggregate motercycle = new Vehicles.Motercycle(); IVehicleIterator carIterator = car.CreateIterator(); IVehicleIterator motercycleIterator = motercycle.CreateIterator(); PrintVehicles(carIterator); PrintVehicles(motercycleIterator); } static void PrintVehicles(IVehicleIterator iterator) { iterator.First(); while (!iterator.IsDone()) { Console.WriteLine(iterator.Next()); } }
Ntabwo tuzi ubwoko bwikusanyirizo, ariko buracyasubirwamo hifashishijwe igishushanyo mbonera cya Iterator. Niba ugiye imbere ukiruka, irerekana ibisohoka bikurikira.
Ukurikije Agatsiko ka Bane, uburyo bwa Mediator bukubiyemo ibintu bikorana.
Igishushanyo mbonera cy'abunzi kidufasha gushushanya porogaramu zidahujwe no guhuza ibintu.
Reka dusuzume urugero rwicyumba cyo kuganiriramo aho abitabiriye biyandikisha, nuburyo bwo kuvugana neza.
Ukeneye gushyira mubikorwa ikiganiro gikurikira ukoresheje Igishushanyo mbonera cya Mediator.
David to Scott: 'Hey' Scott to David: 'I am good how about you.' Jennifer to Ashley: 'Hey ashley... david is back in the group' Jennifer to David: 'Where have you been?' Ashley to David: 'How come you aren't active here anymore?'
Intambwe yambere nugukora urutonde rwamazina azakoreshwa imbere mubiganiro. Ibarura rusange ryibyo birerekanwa hepfo.
public enum Username{ Ashley, David, Jennifer, Scott }
Noneho, mbere na mbere, shyira mubikorwa abstract yo kuganira.
public abstract class AChatroom { public abstract void Register(User user); public abstract void Post(string fromUser, string toUser, string msg); }
N'ishuri risobanura uburyo budafatika. Uburyo bwemeza niba umukoresha abaho mu nkoranyamagambo. Kurugero, uburyo bwo kwiyandikisha bwemeza niba umukoresha asanzweho cyangwa adahari. Niba bidahari, noneho wandike umukoresha mubyumba byose.
public class Chatroom : AChatroom { private Dictionary<string, User> _users = new Dictionary<string, User>(); public override void Post(string fromUser, string toUser, string msg) { User participant = _users[toUser]; if (participant != null) { participant.DM(fromUser, msg); } } public override void Register(User user) { if (!_users.ContainsValue(user)) { _users[user.Name] = user; } user.Chatroom = this; } }
Hanyuma, reka dushyire mubikorwa ibikorwa umukoresha ashobora gukora, nko kohereza ubutumwa kumukoresha mukiganiro cyangwa kwakira DM kubandi bakoresha.
public class User { private Chatroom _chatroom; private string _name; public User(string name) => this._name = name; public string Name => _name; public Chatroom Chatroom { set { _chatroom = value; } get => _chatroom; } public void Post(string to, string message) => _chatroom.Post(_name, to, message); public virtual void DM(string from, string message) => Console.WriteLine("{0} to {1}: '{2}'", from, Name, message); }
static void Main(string[] args) { Chatroom chatroom = new Chatroom(); User Jennifer = new UserPersona(Username.Jennifer.ToString()); User Ashley = new UserPersona(Username.Ashley.ToString()); User David = new UserPersona(Username.David.ToString()); User Scott = new UserPersona(Username.Scott.ToString()); chatroom.Register(Jennifer); chatroom.Register(Ashley); chatroom.Register(David); chatroom.Register(Scott); David.Post(Username.Scott.ToString(), "Hey"); Scott.Post(Username.David.ToString(), "I am good how about you."); Jennifer.Post(Username.Ashley.ToString(), "Hey ashley... david is back in the group"); Jennifer.Post(Username.David.ToString(), "Where have you been?"); Ashley.Post(Username.David.ToString(), "How come you aren't active here anymore?"); Console.ReadKey(); }
Porogaramu ikorwa isobanura gusa uburyo bwa Post bwabakoresha urwego.
Ibisohoka: Amateka yo kuganiriraho ya progaramu yavuzwe haruguru
David to Scott: 'Hey' Scott to David: 'I am good how about you.' Jennifer to Ashley: 'Hey ashley... david is back in the group' Jennifer to David: 'Where have you been?' Ashley to David: 'How come you aren't active here anymore?'
Ukurikije Agatsiko ka Bane, uburyo bw'indorerezi busobanura kwishingikiriza b / w ibintu bibiri cyangwa byinshi. Rero, iyo ikintu kimwe leta ihindutse, noneho abayishingiye bose barabimenyeshwa.
Muyandi magambo, impinduka mubintu bimwe itangiza imenyesha mubindi bintu.
Reka dufate urugero rwumuntu uzwi cyane wa Instagram ufite " x " umubare wabakurikira. Noneho, mugihe ibyamamare byongeyeho inyandiko, noneho abayoboke bose barabimenyeshwa.
Reka dushyire mubikorwa ikibazo cyavuzwe haruguru dukoresheje Igishushanyo mbonera.
Ukurikije ikibazo cyo gukoresha, uwambere ashyira mubikorwa intera ikubiyemo ibikorwa icyamamare gishobora gukora. Bizwi nka “ Subject .”
public interface ICelebrityInstagram{ string FullName { get; } string Post { get; set; } void Notify(string post); void AddFollower(IFollower fan); void RemoveFollower(IFollower fan); }
Menyesha: Kumenyesha abayoboke bose.
Ongeraho Abakurikira: Ongeraho umuyoboke mushya kurutonde rwibyamamare.
Kuraho Abakurikira: Kuraho umuyoboke kurutonde rwibyamamare.
Noneho, shyira mubikorwa indorerezi "IFollower", ikubiyemo imikorere yabanyamuryango "Kuvugurura" kugirango bamenyeshe.
public interface IFollower{ void Update(ICelebrityInstagram celebrityInstagram); }
Hanyuma, igihe kirageze cyo gushyira mubikorwa "Gushyira mubikorwa" kuri " Ikintu " na " Indorerezi ."
Itanga ishyirwa mubikorwa ryimikorere yabanyamuryango, isohora izina ryicyamamare & post kuri konsole.
public class Follower : IFollower { public void Update(ICelebrityInstagram celebrityInstagram) { Console.WriteLine($"Follower notified. Post of {celebrityInstagram.FullName}: " + $"{celebrityInstagram.Post}"); } }
public class Sukhpinder : ICelebrityInstagram { private readonly List<IFollower> _posts = new List<IFollower>(); private string _post; public string FullName => "Sukhpinder Singh"; public string Post { get { return _post; } set { Notify(value); } } public void AddFollower(IFollower follower) { _posts.Add(follower); } public void Notify(string post) { _post = post; foreach (var item in _posts) { item.Update(this); } } public void RemoveFollower(IFollower follower) { _posts.Remove(follower); } }
Urubanza rukoreshwa rukurikira rwerekana ko igihe cyose amagambo akurikira ashyizwe mu bikorwa.Post = “Nkunda ibishushanyo mbonera.”; Uburyo bwo kuvugurura butangirwa kuri buri mukurikira, ni ukuvuga, buri kintu gikurikira kimenyeshwa inyandiko nshya kuva "Sukhpinder."
static void Main(string[] args) { var sukhpinder = new Sukhpinder(); var firstFan = new Follower(); var secondFan = new Follower(); sukhpinder.AddFollower(firstFan); sukhpinder.AddFollower(secondFan); sukhpinder.Post = "I love design patterns."; Console.Read(); }
Ingingo isobanura uburyo guhuza imiterere bitanga uburyo bwiza bwo gukoresha no gutunganya ayo makuru muburyo butari muri sisitemu yibanze.
Reka dufate urugero rwa Toll Calculator hanyuma turebe uburyo guhuza bifasha kwandika algorithm kubyo.
public class Car { public int PassengerCount { get; set; } } public class DeliveryTruck { public int Weight { get; set; } } public class Taxi { public int Fare { get; set; } } public class Bus { public int Capacity { get; set; } public int RidersCount { get; set; } }
Urugero rwa 1: Kubara ibiciro byishyurwa ukurikije ibihe bikurikira:
- Niba ikinyabiziga ari Imodoka => 100
- Niba ikinyabiziga ari DeliveryTruck => 200 amafaranga
- Niba ikinyabiziga ari Bus => 150 amafaranga
- Niba ikinyabiziga ari Tagisi => 120
Niba ubwoko bwimodoka ihuye nimodoka 100 isubizwa & nibindi. Menya ko null & {} ari imanza zidasanzwe kubintu byubwoko.
Na none, "_" irashobora gukoreshwa mugutegura gahunda isanzwe. Reba uburyo bushya bwo guhinduranya.
Nuburyo bwiza cyane kandi bunoze bwo gukora code & nanone twasabye gukoresha amazina yinyuguti imwe ihindura amazina imbere muri syntax.
public static int TollFare(Object vehicleType) => vehicleType switch { Car c => 100, DeliveryTruck d => 200, Bus b => 150, Taxi t => 120, null => 0, { } => 0 };
Gerageza ingero uhereye kumurongo wa porogaramu. Kode ikurikira irerekana uburyo bwo guhamagara imikorere yavuzwe haruguru ihuza uburyo bukuru.
var car = new Car(); var taxi = new Taxi(); var bus = new Bus(); var truck = new DeliveryTruck(); Console.WriteLine($"The toll for a car is {TollFare(car)}"); Console.WriteLine($"The toll for a taxi is {TollFare(taxi)}"); Console.WriteLine($"The toll for a bus is {TollFare(bus)}"); Console.WriteLine($"The toll for a truck is {TollFare(truck)}");
The toll for a car is 100 The toll for a taxi is 120 The toll for a bus is 150 The toll for a truck is 200
Urugero rwa 2: Ongeraho ibiciro byo guturamo ukurikije ubwoko bwimodoka
- Imodoka & tagisi hamwe nabagenzi ba "OYA" bishyura amafaranga 10 yinyongera.
- Imodoka & tagisi hamwe nabagenzi babiri babona kugabanyirizwa amafaranga 10.
- Imodoka & tagisi hamwe nabagenzi batatu cyangwa barenga babona amafaranga 20.
- Bisi zitageze kuri 50% byabagenzi bishyura amafaranga 30 yinyongera.
- Bisi zifite abagenzi barenga 90% zibona amafaranga 40.
- Amakamyo arenga ibiro 5000 yishyurwa amafaranga 100.
- Amakamyo yoroheje munsi y'ibiro 3000, ahabwa kugabanyirizwa amafaranga 20.
Reba ku gishushanyo-gihuza syntax hamwe nimwe & byinshi byumutungo ibyiciro. Ihuza
Car { PassengerCount: 0 } => 100 + 10, Car { PassengerCount: 1 } => 100, Car { PassengerCount: 2 } => 100 - 10, Car c => 100 - 20,
Taxi {Fare:0 }=>100+10, Taxi { Fare: 1 } => 100, Taxi { Fare: 2 } => 100 - 10, Taxi t => 100 - 20,
Bus b when ((double)b.RidersCount / (double)b.Capacity) < 0.50 => 150 + 30, Bus b when ((double)b.RidersCount / (double)b.Capacity) > 0.90 => 150 - 40, Bus b => 150,
DeliveryTruck t when (t.Weight > 5000) => 200 + 100, DeliveryTruck t when (t.Weight < 3000) => 200 - 20, DeliveryTruck t => 200,
Urugero rukurikira rugaragaza ibyiza byo guhuza: amashami yicyitegererezo yakusanyirijwe hamwe. Uwayihimbye kandi araburira kubyerekeye kode itagerwaho.
public static int OccupancyTypeTollFare(Object vehicleType) => vehicleType switch { Car { PassengerCount: 0 } => 100 + 10, Car { PassengerCount: 1 } => 100, Car { PassengerCount: 2 } => 100 - 10, Car c => 100 - 20, Taxi { Fare: 0 } => 100 + 10, Taxi { Fare: 1 } => 100, Taxi { Fare: 2 } => 100 - 10, Taxi t => 100 - 20, Bus b when ((double)b.RidersCount / (double)b.Capacity) < 0.50 => 150 + 30, Bus b when ((double)b.RidersCount / (double)b.Capacity) > 0.90 => 150 - 40, Bus b => 150, DeliveryTruck t when (t.Weight > 5000) => 200 + 100, DeliveryTruck t when (t.Weight < 3000) => 200 - 20, DeliveryTruck t => 200, null => 0, { } => 0, };
Gerageza ingero uhereye kuri konsole ya porogaramu. Kode ikurikira irerekana uburyo bwo guhamagara imikorere yavuzwe haruguru ihuza uburyo bukuru.
var car1 = new Car{ PassengerCount=2}; var taxi1 = new Taxi { Fare = 0 }; var bus1 = new Bus { Capacity = 100, RidersCount = 30 }; var truck1 = new DeliveryTruck { Weight = 30000 }; Console.WriteLine($"The toll for a car is {OccupancyTypeTollFare(car1)}"); Console.WriteLine($"The toll for a taxi is {OccupancyTypeTollFare(taxi1)}"); Console.WriteLine($"The toll for a bus is {OccupancyTypeTollFare(bus1)}"); Console.WriteLine($"The toll for a truck is {OccupancyTypeTollFare(truck1)}");
The toll for a car is 90 The toll for a taxi is 110 The toll for a bus is 180 The toll for a truck is 300
"Guhuza icyitegererezo bituma kode isomeka kandi igatanga ubundi buryo bwo gukoresha ibintu mugihe udashobora kongera kode mumasomo yawe."
Agatsiko ka Bane - Igishushanyo mbonera cya Singleton cyemeza ko icyiciro runaka gifite urugero / ikintu kimwe gusa hamwe nokugera kwisi yose.
Ibyiciro bya Singleton bikoreshwa mugukuraho guhita kurenga ikintu kimwe cyicyiciro runaka.
public class SingletonExample { private string Name { get; set; } = "Hello from singleton"; private static SingletonExample _instance; public static SingletonExample Instance { get { if (_instance == null) { _instance = new SingletonExample(); } return _instance; } } public SingletonExample() { } public string GetName() => Name; }
Reka duhamagare icyiciro cya singleton inshuro ebyiri hanyuma dushyireho urugero rwagarutse kubintu bibiri bitandukanye. Hanyuma, reba niba ibintu byombi bingana ukoresheje Ikintu.Ibikorwa bingana.
static void Main(string[] args) { var response = SingletonExample.Instance; Console.WriteLine(response); var response1 = SingletonExample.Instance; Console.WriteLine(response1); Console.WriteLine(Object.Equals(response1, response)); }
Ibisohoka bya konsole bisubiza ukuri; twishimiye. Washyize mubikorwa neza icyitegererezo cya Singleton.
Icyiciro cyavuzwe haruguru kizwi nkicyiciro cya singleton, ariko kuri ubu, ntabwo gifite umurongo-umutekano. Mubidukikije-byinshi-bidukikije, insanganyamatsiko ebyiri zirashobora gukubita niba (_instance == null) imvugo icyarimwe, kandi tuzarangiza dufite ingero nyinshi zicyiciro kimwe.
Inzira imwe kumurongo utekanye ni ugukoresha uburyo bwo gufunga, naho ubundi ni ugukora urugero rwasomwe gusa kugirango hasukure kandi neza.
public class ThreadSafeSingleton { private static readonly ThreadSafeSingleton _instance = new ThreadSafeSingleton(); public static ThreadSafeSingleton Instance { get { return _instance; } } public ThreadSafeSingleton() { } }
https://github.com/ssukhpinder/Ibishushanyo mbonera
Abaterankunga bamfasha gukomeza kubungabunga no kubaka imishinga mishya nkiyi.
🙏 Niba ukoresha Kwishura, Kumenyeshwa, cyangwa ikindi gikorwa cyanjye, umusanzu muto wasobanura BYINSHI. Kubwonyine, isoko-ifunguye ntabwo yishyura fagitire. Twizere ko, ubufasha bwawe, gukomeza akazi kanjye birashobora kuramba, kandi sinzakenera kujya kubona akazi nyako 😛.
Urakoze kuba umwe mubagize umuryango C #!