Strategy Pattern
I will try to explain this pattern as simple as I can because it is really simple and useful. Lets define a problem: Think about that you have employees in different departments with different titles and you need a method which calculates different salaries.
Answer 1 – You can write a method which takes the jobType parameter and you can calculate different salaries with one method. The main disadvantage of this way is that the main class must know all parameters. Also it’s hard to add new job type – you need to add new parameters and methods into the class.
Answer 2 – You can use inheritence. Create an Employee class and extend it with the other employee type classes. Each of them has its own method so you do’nt need any parameter. But what if you want to add a new method to calculate holidays of different departments? For this answer, you must create another employee class and its subclasses because each employee belongs the same department in this solution.
Answer 3- USE STRATEGY PATTERN! In this solution, create an employee class and two more classes which extend this class: Salary class and Holidays class. Salary class is implemented by job type classes and holidays class is implemented by departments. Lets give a try.
1 2 3 4 5 6 7 8 9 |
public interface ISalary { public int calculateSalary(); } public interface IHolidays{ public int calculateHolidays(); } |
These two interfaces give us methods which will be used in classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class EmlpoyeeASalary : ISalary { public int calculateSalary() { return 1234; } } public class EmlpoyeeBSalary : ISalary { public int calculateSalary() { return 2345; } } public class EmlpoyeeCSalary : ISalary { public int calculateSalary() { return 3456; } } public class DepartmentAHolidays : IHolidays { public int calculateHolidays() { return 15; } } public class DepartmentBHolidays : IHolidays { public int calculateHolidays() { return 20; } } |
Now, we can create Employee class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Employee{ public ISalary salary; public IHolidays holidays; public Employee(ISalary _salary, IHolidays _holidays) { salary = _salary; holidays = _holidays; } public int calcSalary(){ return salary.calculateSalary(); } public int calcHolidays(){ return holidays.calculateHolidays(); } } |
Finally, we can create our objects and call their methods in Main class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class MainClass { Employee employee1 = new Employee(new EmployeeASalary(), new DepartmentAHolidays()); int salaryA = employee.calculateSalary(); int holidayA = employee.calculateHolidays(); Employee employee2 = new Employee(new EmployeeBSalary(), new DepartmentAHolidays()); int salaryB = employee.calculateSalary(); int holidayA = employee.calculateHolidays(); Employee employee3 = new Employee(new EmployeeCSalary(), new DepartmentBHolidays()); int salaryC = employee.calculateSalary(); int holidayB = employee.calculateHolidays(); } |
In this part, you have 3 different employee types in different departments. You can also use int values separately. You can see class diagram of this example.
©Coffee Break Codes – C# Design Patterns in Unity3D : Strategy Pattern
Hi,
Thank you for your great topic. I think it is better, for sake of encapsulation in Employee class use:
private ISalary salary;
private IHolidays holidays;
and in MainClass you must change it to :
Employee employee1 = new Employee(new EmlpoyeeASalary(), new DepartmentAHolidays());
int salaryA = employee1.CalcSalary();
int holidayA = employee1.CalcHolidays();
Employee employee2 = new Employee(new EmlpoyeeBSalary(), new DepartmentAHolidays());
int salaryB = employee2.CalcSalary();
int holidayB = employee2.CalcHolidays();
Employee employee3 = new Employee(new EmlpoyeeCSalary(), new DepartmentBHolidays());
int salaryC = employee3.CalcSalary();
int holidayC = employee3.CalcHolidays();
On another call pthc blowjob Corbin, who was appointed chairman of a city commission under Filner, declined to say if he voted for Filner or how he would cast his ballot in a recall. He said his motive was to bring swift resolution to the controversy.
How do I get an outside line? beautiful scene wallpaper full hd Mr Sarkozy made no reaction, but his closest lieutenants, Brice Hortefeux said: “François Fillon worked under Nicolas Sarkozy for five years. So if there is criticism, it should start by self-criticism.”
Do you have any exams coming up? wallpaper ungu pastel polos The soldiers, part of the NATO-led International Security Assistance Force (ISAF), where killed in Paktia province, where Afghan soldiers have taken on increasingly more responsibility for security and the fight against insurgents.
I do some voluntary work pc wallpaper full hd 2018 The banking union is believed to be able to help stabilize the bloc’s financial system. Members of the Parliament will vote later this week on the legislation establishing a centralized oversight for the EU’s largest banks, considered as a first step for the banking union.
I’d like to transfer some money to this account indianactress wallpaper The league also believes A-Rod violated the âjust causeâ provision (Rule 7G.2) of the collective bargaining agreement between the league and its union by obstructing commissioner Bud Seligâs investigation and lying to officials about doping, adding another 50-plus games to the suspension. Rodriguez is expected to be suspended under both provisions.
One moment, please wallpaper hd desktop tumblr “At one point, Chris squeezes my glove with his and I give him the universal ‘OK’ sign with mine. The last time he heard me speak was before entering the airlock!” Parmitano says, recounting his interaction with American colleague Chris Cassidy, who joined him on what was supposed to be a routine maintenance mission to investigate a leak.
Pleased to meet you unbelievable wallpapers free download Bets on the royal baby’s name are one of Paddy Power’s biggest “Royal Special” pools, with “Alexandra” (7/4), “Charlotte” (5/1) and “James” (8/1) topping the odds. However, Scott says “Diana” (11/1) has actually taken the most volume of bets, many of them much smaller, perhaps reflecting a British desire to honor William’s late mother, the beloved Princess Diana.
I’ll put him on free wallpapers cottages “Another Warrior, another MC of the Funk spiritually leaves us unexpectantly [sic],” a friend left on the artist’s Facebook page. “He left the stage without saying goodbye, a victim of intolerance! A great loss to our family of Funk!”
Could you transfer $1000 from my current account to my deposit account? vista wallpaperz What does this mean? By definition, at least, psychopathology and normalcy would appear to be mutually exclusive. Yet some of our most insightful thinkers have reasoned otherwise. In these examples, they have willingly looked beyond the seductive veneers of orthodox psychological investigation.
I’ve got a very weak signal 800 x 600 and 1024 x 768 wallpapers But the U.S. Treasury was forced to pay the highest interest rate in about 10 months on its short-term debt as many investors avoided bonds that would be due later this month, when the government is due to exhaust its borrowing capacity.
Whereabouts in are you from? baby lions wallpaper “It is with great sadness that we have to announce that Jon Brookes, the drummer with The Charlatans, died this morning aged 44. He passed away peacefully in hospital early this morning with his family at his bedside.”
perfect design thanks joanna aimee wallpaper Back when Microsoft was the biggest name in technology, CEO Bill Gates leveled an attack on the auto industry: If carmakers were as innovative as computer companies, he said, a car would cost just $27.
I’ve been cut off how big is an iphone wallpaper Shares of most major weapons makers rose on Wednesday, butGeneral Dynamics shares closed 2.2 percent lower at $86.23, amidconcerns about its combat systems business, which saw quarterlyrevenues drop 30 percent.
I work for myself wallpaper acche wale Army Col. Denise Lind began deliberating Friday after nearly two months of conflicting evidence and arguments about the 25-year-old intelligence analyst. A military judge, not a jury, is hearing the case at Manning’s request.
real beauty page french chef wallpaper But if Peña Nieto had been forced to change his plans and issue his first Cry of Independence anywhere but the Zocalo, it probably would have been seen as an embarrassing sign of weakness. Critics were quick to mock Peña Nieto this month when the teachers sit-in forced him to move his first state of the nation address from the National Palace to Los Pinos, the official presidential residence a few miles away.
What company are you calling from? superfresco paintable wallpaper uk “I know if it’s not going right then he’s going to throw me back at the four,” Anthony said. “So my mindset is just be prepared for that. If that times comesâ¦when that time comes, I’ll just slide back over in any position, whether it’s the three or the four.”
Where are you from? wallpaper rotator apk The troubles also hit Google Docs and Google Presentations. The company did not elaborate on the problems with those features, except to say there was an “issue.” As of 12:43 p.m. Eastern, Google said its team was still investigating the problems and would provide an update at 1:45 p.m.
Where’s the postbox? raikonen wallpapers Brazilian-born Mike Krieger had moved to America to attend Stanford, where the pair met, and wrote his thesis on how user interfaces could be harnessed on a large scale. He interned at Microsoft and worked for instant messaging firm Meebo after graduating.
I’d like to tell you about a change of address iraj nozari wallpapers All things, say some, that Apple was put on this earth tofix. Ben Thompson, a Taipei-based industry observer who writes ablog at stratechery.com, said Apple was focusing on theapparently trivial problem of entering a password – but one thatirked users dozens of times a day.
this post is fantastic informatique wallpapers Latos tweeted she was âpunched in the head at least three timesâ by a Pirates fan and her hair was pulled, writing âIâm âfineâ but my head hurts. Never swung back bc I was trying to protect myself.â
I’ve just started at peanuts kostenlose wallpaper downloud * Halliburton Co has agreed to plead guilty todestruction of critical evidence after the Gulf of Mexico spillin 2010. The oil services company will pay the maximum allowablefine and be subject to three years of probation, the JusticeDepartment said. ()
Best Site good looking punith hd wallpapers The data discrepancy dates back to Indonesia’sdecentralization of the mining sector in 2004, when control overmineral resources shifted to regional administrations, saidXavier Jean, credit analyst at Standard & Poor’s.
Would you like a receipt? berserk wallpaper 4k Theyâre the male version of the quirky, meddling, impossible mothers who are a staple of dramas from âRizzoli & Islesâ to âCastle.â While those mothers eventually become oddly endearing, this is MacFarlane. So weâll see.
How long have you lived here? csgo wallpaper iphone 5 Thailand’s Anti-Money Laundering Office has discovered 41 bank accounts linked to the ex-monk. Several of the accounts kept about 200 million baht ($6.4 million) in constant circulation, raising suspicion of money laundering.
I’d like to apply for this job free husker football wallpaper He laid out the intelligence supporting the US contention that Assad was responsible; he set down the moral case to act on behalf of the father “clutching his dead children, imploring them to get up and walk” and dwelled on the historical responsibility to uphold global prohibitions on using chemical weapons.
Would you like to leave a message? wallpaper exo terbaru 2017 Ten days after Al Qaeda chief Ayman al-Zawahiri called on radical Islamists to stage guerrilla-style attacks, gunmen laid siege to the Westgate Mall in Kenya, killing at least 61 people, including women and children and, in line with the terror groupâs current instructions, aiming to kill only infidels.
I love the theatre christmas countdown wallpaper for iphone As originally written, the law required a convicted drunk to install on his or her vehicle an ignition interlock device, a kind of Breathalyzer, for six to 12 months, depending on the level of drunkenness.
Best Site Good Work wallpapers draculaura Returning to America after his release from Frascati in 1953, Davis wrote his first book and launched an unsuccessful court bid to reverse his “excludable alien” status. In 1986 he ran for mayor of Washington, DC, as the World Citizen Party candidate, receiving 585 votes; he stood for US president in 1988. Upon the re-election of Ronald Reagan he moved to Vermont, his home for the last two decades.
US dollars hd rose wallpapers images âWe use the show to make jokes, but the jokes are things that we care about because we are writing about the news, and you can’t do 160 (shows) a year unless you have some passion of what you are talking about,â he said backstage after winning an Emmy for Outstanding Variety Series, responding to a question about whether he uses his platform to promote his personal convictions, such as the time he took his mock conservative shtick to Congress to testify on illegal immigration. âI’m not trying to make a point; I’m trying to make a joke. Sometimes my personal views are what I am saying, but it is important to me that you never know when that is.”
I’m only getting an answering machine sky full hd wallpaper While in Senegal, they encountered gold miners who would descend small narrow shafts that could extend 20m (65ft) down into the earth where they would extract chunks of gold-bearing quartz. This is then mixed with a mercury amalgam to separate the gold.
I’d like to open an account free babes wallpapers âThis seems like a development wolf in a sheepâs storm boots,â said Phillip Musegaas, the Hudson River Director at Riverkeeper, the self-styled stewards of the tidal estuary with the river name. âThe mayor likes big development projects, and he just sees this as another opportunity to burnish his legacy.â
Looking for work lebron james wallpaper hd 2017 Whitten also acknowledged Microsoft’s failure in accurately demonstrating and communicating the Xbox One’s features. âI think itâs pretty simple. Weâve got to just talk more, get people understanding what our system is,â he said. âThe thing thatâs really gratifying is that people are excited about the types of features that are possible, and Itâs sort of shame on us that we havenât done as good of a job as we can to make people feel like thatâs where weâre headed.â
A company car cute pikachu wallpapers Danny Garcia is the underdog in the fight, which he also was before he stopped Khan in just four rounds last year. But heâs eager to get in the ring with Matthysse to see if the hype he has generated is warranted.
We went to university together almas name wallpaper To save time, yacht builders have advanced methods for pre-impregnating resins in carbon-fiber fabric to shorten and simplify the process of laying the fabric around a rigid honeycomb core and hardening the layers together in a mold. This cuts out the costly, time-consuming process of heating the composites in ovens.
Pleased to meet you philadelphia theme desktop wallpapers Verizon was named in documents released by fugitive formerU.S. spy agency contractor Edward Snowden that detailedelectronic spying operations by the U.S. National SecurityAgency, including a vast log of phone calls by its customers.
A pension scheme how to protect wallpaper in a bathroom In 2012, the government settled False Claims Act mortgage cases for $1 billion with Bank of America, $202.3 million with Deutsche Bank AG, $158.3 million with Citigroup Inc and $132.8 million with Flagstar Bancorp Inc.
This is your employment contract www holi wallpaper photo com Engvall will celebrate 1982, the year the pair got married with a waltz to “She’s Always a Woman” by Billy Joel. The crowd will definitely be rooting for this surprising dance star – no joking there.
I’m afraid that number’s ex-directory free download easter wallpapers A phone message left for a spokeswoman for the U.S. Attorney’s Office was not immediately returned Tuesday night. A message left for Dzhokhar Tsarnaev’s federal public defender was also not immediately returned.
I can’t get a dialling tone hard work hd wallpapers 1920×1080 âInitially I was very annoyed by her,â says Lewis, who is known for his West Coast sleek, modern style. âSheâs a mom that lives in a Midwestern suburb. The things that are important to her are not important to me.â
I’m originally from Dublin but now live in Edinburgh art atreyu digital wallpaper While his attempt to shift the conversation away from the inflammatory, unproductive argument about race is admirable (especially considering the fact that he so willingly entered that conversation last March), we all know where the Presidentâs call for gun control after the Sandy Hook shooting landed him: Precisely, exactly, nowhere.
What sort of music do you like? 3d live wallpaper Nasdaq has been diversifying away from its traditional stocktransaction business for years, even before volumes plungedduring the global economic crisis, and into businesses thatprovide a steadier income flow.
Can I call you back? sunshine wallpaper images hd “It’s hell here…religion’s the elephant in the room no one talks about,” says Nadi Atef, a writer and activist from Ayman Labib’s town. “I know Egypt’s mostly hell for a Muslim too, but it’s at least a Muslim hell.”
Could I borrow your phone, please? anime shizuo wallpaper “It does seem to close down the options for Carrefour,”Exane BNP analyst Andrew Gwynn said. “That’s not to say therearen’t other potential partners but clearly Carrefour has alsobeen looking for someone to help share.”
I’ve been made redundant toplist bbs He apparently was referring to Aug. 4 attacks on a military base at Malam Fatori and a police outpost in Bama, both near the border with Cameroon. Joint Task Force spokesman Lt. Col. Sagir Musa told reporters 32 extremists, two soldiers and one police officer were killed. But when the Borno state governor called on the head of the task force to commiserate, Maj. Gen. Jah Ewansiah told him in front of reporters that they lost 12 soldiers and seven policemen. Nigeria’s military regularly lowballs casualty figures of civilians and military.
Nice to meet you nudist camp lollita pics Mrs. Obama was joined by retired NBA center Shaquille O’Neal and two Olympians, sprinter Allyson Felix and gymnast Dominique Dawes. All four later changed into sweat clothes to run dozens of the elementary school pupils through a series of aerobic exercise drills.
I’m sorry, I’m not interested lol top ukrainian nymphets The stunt was a success – the story went around the world. About a week later I received a letter, which I still have, from the Prince’s equerry thanking me. But alas the night did not work out and after a couple of months I admitted defeat and went back to selling life insurance.
Good crew it’s cool 🙂 what is nizagara gold 120 Selwyn Soe, who runs The Herbal Factory, a contract manufacturer of herbal remedies in Croydon, south London, said: âUnfortunately it looks as if we will have to close down because of this legislation.â
A company car nizagara 25 Safety equipment will also take a step up in MINI’s next model range too, with a stronger construction to help in an impact as well a system that pops the bonnet up to help absorb the force of a collision.
Who do you work for? hussyfan little girls For goodness sake – this administration has demonstrated time and time again that they are not in touch with the economy, the majority of the U.S. citizens, world politics, the constitution, the best interests of our nation and the needs of our nation to protect our people serving us overseas! This POS administration (especially Obummer, Hillarity Clinton, Nancy Piglosi, gun runner Holder, Lurch Kerry, Stooge Joe (Larry) Biden their IRS and FBI stooges) has amply demonstrated that they have no respect for the constitution, the principles our nation was founded upon, nor the “by the people and for the people” basis established by our founding fathers! Obama should be impeached, H. Clinton and E. Holder should be indicted and this administration should be demolished like the gang of mafia thieves that they are!
Nice to meet you vad oar nizagara The Church, he said, should see itself as “a field hospital after a battle” and try to heal the larger wounds of society and not be “obsessed with the transmission of a disjointed multitude of doctrines to be imposed insistently.”
Have you read any good books lately? lol post bbs lol bbs Though he’s still not playing legitimate NBA-level competition, Zeller is doing things his critics said he wouldn’t be able to do. He’s finishing strong after contact, controlling the glass and holding his own on the physical interior.
Did you go to university? lol rompl dorki sets “Yahoo! Sites and Google Sites have been close for several months, and there is no one single factor that caused Yahoo! to take the number one spot this month,” said Andrew Lipsman, a vice president with comScore. “It is a large network and many of its channels saw gains this month.”
Is there ? super nizagara “I’m pleased to announce that today, very quickly, we were able to agree to a resumption of the strategic dialogue in order to foster a deeper, broader and more comprehensive partnership between our countries,” Kerry said at a press conference with Aziz in Islamabad.
I don’t like pubs al4a mobile
Defense was the story for the eighth-ranked Cardinals (6-0, 2-0 American Athletic Conference), who had four interceptions, sacked Gary Nova eight times and held Rutgers to 12 yards rushing. Pryor led Louisvilleâs stifling effort with 14 tackles and the first late-game interception in holding the Scarlet Knights to 240 yards.
I live here cialisn soft The standoff, prompted by Republicans’ determination to haltPresident Barack Obama’s healthcare reforms, appeared to bemerging with a more complex fight looming later this month overraising the federal debt limit. Some feared this could stymieany attempts to end the shutdown before the middle of October.
I’d like to send this parcel to nizagara information Kidd is expected to lose his driverâs license for 90 days, but could be eligible for a conditioned license. But still: He walks into the courtroom on Tuesday because he was one of the lucky ones, one of those who walked away from a wrecked car in one piece. Single car accident, close to his Water Mill home. The only victims were the car and the tree. It could have been so much worse.
I’ve got a full-time job torono cialis âYou can puree strawberries and raspberry, add a little bit of lime juice, maybe some honey or agaveâ¦and pop it in the freezer,â Flanzraich said. âSo now youâve got this much healthier version of what you wouldâve grabbed.â
Where did you go to university? bbs lola ls magazine One day, alone in a room, he practiced the âcapitalistâ piano piece. He was hoping it would help him woo a woman he loved. Outside, a snitch heard the saccharin melody, and then reported the instrumentalist to authorities.
I went to wallpaper after plastering Merger activity helped boost technology stocks withInvensys up 1.2 percent on reports General Electric may lodge a $5.3 billion, bid that could trigger a battlefor the British software company with France’s SchneiderElectric.
Could you send me an application form? letairis and adcirca He said while pensions auto-enrolment meant more than a million employees were now saving, the Institute’s research showed they were unlikely to be saving anywhere near enough to live comfortably in retirement.
How long have you lived here? sildalis super power erfahrungen Approval ultimately lies with the Committee on ForeignInvestment in the United States (CFIUS), the interagency panelheaded by the U.S. Treasury that reviews foreign investments fornational security threats.
Punk not dead priligy costo en ecuador They needed help. They needed someone who doesnât trust Major League Baseballâs investigation of Biogenesis, someone who thinks Anthony Bosch is a criminal with no credibility. They needed someone who believes the Yankees overstated the severity of Rodriguezâs quad injury for financial reasons. They needed someone to portray A-Rod as a martyr.
I’m originally from Dublin but now live in Edinburgh adcirca medscape Lixil, formed by mergers of several Japanese buildingproduct makers with a product line-up ranging from high-techtoilets to window frames, said the deal valued all of Grohe at3.06 billion euros, or 10.3 times its 2013 earnings beforeinterest, taxes, depreciation and amortization.