C# Design Patterns in Unity3D : Strategy Pattern


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.

These two interfaces give us methods which will be used in classes.

Now, we can create Employee class.

Finally, we can create our objects and call their methods in Main class.

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.

strategy

 

 

©Coffee Break Codes – C# Design Patterns in Unity3D : Strategy Pattern


Leave a comment

Your email address will not be published. Required fields are marked *

64 thoughts on “C# Design Patterns in Unity3D : Strategy Pattern

  • Hadi GHasemiZadeh

    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();

  • Colin

    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.

  • Willian

    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.

  • Peyton

    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.

  • Fritz

    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.

  • Spencer

    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.

  • Antone

    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.

  • Gayle

    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!”

  • Hector

    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.

  • Lyman

    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.”

  • Garland

    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.

  • Leopoldo

    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.

  • Sylvester

    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.”

  • Spencer

    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.

  • Julian

    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.

  • Bob

    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.

  • Rodrigo

    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.”

  • Dro4er

    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.

  • Jamey

    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.

  • Gavin

    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.

  • Chong

    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.

  • Abigail

    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.

  • Jason

    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.

  • Conrad

    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.”

  • Vida

    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.

  • Dillon

    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.”

  • Stephan

    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.”

  • Kirby

    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.

  • Hannah

    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.

  • Joshua

    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.

  • Carmine

    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.”

  • Alexa

    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.

  • Sonny

    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.

  • Nelson

    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.

  • Teddy

    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.

  • Emmett

    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!

  • James

    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.”

  • Florencio

    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.

  • Willie

    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.”

  • Edgardo

    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.

  • Levi

    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.

  • Darwin

    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.

  • Alvaro

    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.

  • Edison

    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.”

  • Lyndon

    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.

  • Kasey

    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.

  • Gregory

    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.

  • Alexis

    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.