Skip to content

Instantly share code, notes, and snippets.

@AleBles
Last active May 25, 2016 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AleBles/396ca8f9dd2bea2defff730588d7fd3d to your computer and use it in GitHub Desktop.
Save AleBles/396ca8f9dd2bea2defff730588d7fd3d to your computer and use it in GitHub Desktop.
CatManager singleton
class Cat {
public age: number = 0;
}
class CatManager {
private static instance: CatManager;
private catPool: Cat[] = [];
constructor() {}
public static getInstance(): CatManager {
if(!CatManager.instance){
CatManager.instance = new CatManager();
}
return CatManager.instance;
}
public generateNewCats(amount: number = 1) {
for (let i: number = 0; i < amount; i++) {
this.catPool.push(new Cat());
}
}
public getCats(minAge?: number = 0, maxAge?: number = 999): Cat[] {
return this.catPool.filter((cat: Cat) => {
return cat.age > minAge && cat.age < maxAge;
});
}
public incrementAges(years: number = 1): void {
this.catPool.forEach((cat: Cat): void => {
cat.age += years;
});
}
}
//State 1
let cm: CatManager = CatManager.getInstance();
cm.generateNewCats(5); //Create 5 cats
cm.incrementAges(2); //age all cats by 4 years
//State 2
let cm: CatManager = CatManager.getInstance();
cm.generateNewCats(3); //Create 3 cats
cm.incrementAges(4); //Now age all 8 cats by another 4 years
let cats: Cat[] = cm.getCats(5); //Fetch the cats who are at minimal 5 years old, should only fetch the cats created in state one
console.log(cats);//This logs: [Cat, Cat, Cat, Cat, Cat], the 5 cats we initialy created in the previous state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment